diff --git a/docs/dialogflowcx_v3/agents.rst b/docs/dialogflowcx_v3/agents.rst index fbd83fe0..4deb1730 100644 --- a/docs/dialogflowcx_v3/agents.rst +++ b/docs/dialogflowcx_v3/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/entity_types.rst b/docs/dialogflowcx_v3/entity_types.rst index c6b68f5d..08e4b6e8 100644 --- a/docs/dialogflowcx_v3/entity_types.rst +++ b/docs/dialogflowcx_v3/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/environments.rst b/docs/dialogflowcx_v3/environments.rst index fc10a8e8..246ee15a 100644 --- a/docs/dialogflowcx_v3/environments.rst +++ b/docs/dialogflowcx_v3/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.environments.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/experiments.rst b/docs/dialogflowcx_v3/experiments.rst index 6f13e0ab..5cba0e2a 100644 --- a/docs/dialogflowcx_v3/experiments.rst +++ b/docs/dialogflowcx_v3/experiments.rst @@ -5,7 +5,6 @@ Experiments :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.experiments.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/flows.rst b/docs/dialogflowcx_v3/flows.rst index 832a92cd..77f6398e 100644 --- a/docs/dialogflowcx_v3/flows.rst +++ b/docs/dialogflowcx_v3/flows.rst @@ -5,7 +5,6 @@ Flows :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.flows.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/intents.rst b/docs/dialogflowcx_v3/intents.rst index e5521b4a..8b9e6dda 100644 --- a/docs/dialogflowcx_v3/intents.rst +++ b/docs/dialogflowcx_v3/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/pages.rst b/docs/dialogflowcx_v3/pages.rst index 6ed56180..0bbfbced 100644 --- a/docs/dialogflowcx_v3/pages.rst +++ b/docs/dialogflowcx_v3/pages.rst @@ -5,7 +5,6 @@ Pages :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.pages.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/security_settings_service.rst b/docs/dialogflowcx_v3/security_settings_service.rst index 6e9967b8..4b4fa007 100644 --- a/docs/dialogflowcx_v3/security_settings_service.rst +++ b/docs/dialogflowcx_v3/security_settings_service.rst @@ -5,7 +5,6 @@ SecuritySettingsService :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.security_settings_service.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/session_entity_types.rst b/docs/dialogflowcx_v3/session_entity_types.rst index d92d0fe5..46ff0f6e 100644 --- a/docs/dialogflowcx_v3/session_entity_types.rst +++ b/docs/dialogflowcx_v3/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.session_entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/test_cases.rst b/docs/dialogflowcx_v3/test_cases.rst index ab5a6fbb..3cad4dd4 100644 --- a/docs/dialogflowcx_v3/test_cases.rst +++ b/docs/dialogflowcx_v3/test_cases.rst @@ -5,7 +5,6 @@ TestCases :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.test_cases.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/transition_route_groups.rst b/docs/dialogflowcx_v3/transition_route_groups.rst index 437962a6..d5549da9 100644 --- a/docs/dialogflowcx_v3/transition_route_groups.rst +++ b/docs/dialogflowcx_v3/transition_route_groups.rst @@ -5,7 +5,6 @@ TransitionRouteGroups :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.transition_route_groups.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/versions.rst b/docs/dialogflowcx_v3/versions.rst index 10f422b8..2d72f02d 100644 --- a/docs/dialogflowcx_v3/versions.rst +++ b/docs/dialogflowcx_v3/versions.rst @@ -5,7 +5,6 @@ Versions :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.versions.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3/webhooks.rst b/docs/dialogflowcx_v3/webhooks.rst index 53f893eb..2e2f9b8c 100644 --- a/docs/dialogflowcx_v3/webhooks.rst +++ b/docs/dialogflowcx_v3/webhooks.rst @@ -5,7 +5,6 @@ Webhooks :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3.services.webhooks.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/agents.rst b/docs/dialogflowcx_v3beta1/agents.rst index f1f6e5e9..511ac6f9 100644 --- a/docs/dialogflowcx_v3beta1/agents.rst +++ b/docs/dialogflowcx_v3beta1/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/entity_types.rst b/docs/dialogflowcx_v3beta1/entity_types.rst index 27814dcd..3878a96e 100644 --- a/docs/dialogflowcx_v3beta1/entity_types.rst +++ b/docs/dialogflowcx_v3beta1/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/environments.rst b/docs/dialogflowcx_v3beta1/environments.rst index eeb8ed19..0e31d34d 100644 --- a/docs/dialogflowcx_v3beta1/environments.rst +++ b/docs/dialogflowcx_v3beta1/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.environments.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/experiments.rst b/docs/dialogflowcx_v3beta1/experiments.rst index fc67280f..5c185e4f 100644 --- a/docs/dialogflowcx_v3beta1/experiments.rst +++ b/docs/dialogflowcx_v3beta1/experiments.rst @@ -5,7 +5,6 @@ Experiments :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.experiments.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/flows.rst b/docs/dialogflowcx_v3beta1/flows.rst index ef180bee..0183ff3b 100644 --- a/docs/dialogflowcx_v3beta1/flows.rst +++ b/docs/dialogflowcx_v3beta1/flows.rst @@ -5,7 +5,6 @@ Flows :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.flows.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/intents.rst b/docs/dialogflowcx_v3beta1/intents.rst index 4e4f0077..3bf9d37c 100644 --- a/docs/dialogflowcx_v3beta1/intents.rst +++ b/docs/dialogflowcx_v3beta1/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/pages.rst b/docs/dialogflowcx_v3beta1/pages.rst index 780bcf97..be3f1b16 100644 --- a/docs/dialogflowcx_v3beta1/pages.rst +++ b/docs/dialogflowcx_v3beta1/pages.rst @@ -5,7 +5,6 @@ Pages :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.pages.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/security_settings_service.rst b/docs/dialogflowcx_v3beta1/security_settings_service.rst index 560a3364..0489568a 100644 --- a/docs/dialogflowcx_v3beta1/security_settings_service.rst +++ b/docs/dialogflowcx_v3beta1/security_settings_service.rst @@ -5,7 +5,6 @@ SecuritySettingsService :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.security_settings_service.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/session_entity_types.rst b/docs/dialogflowcx_v3beta1/session_entity_types.rst index b4c42ef9..a6248835 100644 --- a/docs/dialogflowcx_v3beta1/session_entity_types.rst +++ b/docs/dialogflowcx_v3beta1/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.session_entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/test_cases.rst b/docs/dialogflowcx_v3beta1/test_cases.rst index 0840b07a..a212f0b4 100644 --- a/docs/dialogflowcx_v3beta1/test_cases.rst +++ b/docs/dialogflowcx_v3beta1/test_cases.rst @@ -5,7 +5,6 @@ TestCases :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.test_cases.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/transition_route_groups.rst b/docs/dialogflowcx_v3beta1/transition_route_groups.rst index 894278a4..9b29ddf9 100644 --- a/docs/dialogflowcx_v3beta1/transition_route_groups.rst +++ b/docs/dialogflowcx_v3beta1/transition_route_groups.rst @@ -5,7 +5,6 @@ TransitionRouteGroups :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/versions.rst b/docs/dialogflowcx_v3beta1/versions.rst index c08e348c..6617fb66 100644 --- a/docs/dialogflowcx_v3beta1/versions.rst +++ b/docs/dialogflowcx_v3beta1/versions.rst @@ -5,7 +5,6 @@ Versions :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.versions.pagers :members: :inherited-members: diff --git a/docs/dialogflowcx_v3beta1/webhooks.rst b/docs/dialogflowcx_v3beta1/webhooks.rst index d5a82452..4fa96e0f 100644 --- a/docs/dialogflowcx_v3beta1/webhooks.rst +++ b/docs/dialogflowcx_v3beta1/webhooks.rst @@ -5,7 +5,6 @@ Webhooks :members: :inherited-members: - .. automodule:: google.cloud.dialogflowcx_v3beta1.services.webhooks.pagers :members: :inherited-members: diff --git a/google/cloud/dialogflowcx/__init__.py b/google/cloud/dialogflowcx/__init__.py index cd27a417..8804b06e 100644 --- a/google/cloud/dialogflowcx/__init__.py +++ b/google/cloud/dialogflowcx/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,62 +14,63 @@ # limitations under the License. # -from google.cloud.dialogflowcx_v3.services.agents.async_client import AgentsAsyncClient 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.entity_types.client import EntityTypesClient from google.cloud.dialogflowcx_v3.services.entity_types.async_client import ( EntityTypesAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient from google.cloud.dialogflowcx_v3.services.environments.async_client import ( EnvironmentsAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.environments.client import EnvironmentsClient +from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient from google.cloud.dialogflowcx_v3.services.experiments.async_client import ( ExperimentsAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.experiments.client import ExperimentsClient -from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient from google.cloud.dialogflowcx_v3.services.flows.client import FlowsClient +from google.cloud.dialogflowcx_v3.services.flows.async_client import FlowsAsyncClient +from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient from google.cloud.dialogflowcx_v3.services.intents.async_client import ( IntentsAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.intents.client import IntentsClient -from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient from google.cloud.dialogflowcx_v3.services.pages.client import PagesClient -from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import ( - SecuritySettingsServiceAsyncClient, -) +from google.cloud.dialogflowcx_v3.services.pages.async_client import PagesAsyncClient from google.cloud.dialogflowcx_v3.services.security_settings_service.client import ( SecuritySettingsServiceClient, ) -from google.cloud.dialogflowcx_v3.services.session_entity_types.async_client import ( - SessionEntityTypesAsyncClient, +from google.cloud.dialogflowcx_v3.services.security_settings_service.async_client import ( + SecuritySettingsServiceAsyncClient, ) from google.cloud.dialogflowcx_v3.services.session_entity_types.client import ( SessionEntityTypesClient, ) +from google.cloud.dialogflowcx_v3.services.session_entity_types.async_client import ( + SessionEntityTypesAsyncClient, +) +from google.cloud.dialogflowcx_v3.services.sessions.client import SessionsClient from google.cloud.dialogflowcx_v3.services.sessions.async_client import ( SessionsAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.sessions.client import SessionsClient +from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient from google.cloud.dialogflowcx_v3.services.test_cases.async_client import ( TestCasesAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.test_cases.client import TestCasesClient -from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import ( - TransitionRouteGroupsAsyncClient, -) from google.cloud.dialogflowcx_v3.services.transition_route_groups.client import ( TransitionRouteGroupsClient, ) +from google.cloud.dialogflowcx_v3.services.transition_route_groups.async_client import ( + TransitionRouteGroupsAsyncClient, +) +from google.cloud.dialogflowcx_v3.services.versions.client import VersionsClient from google.cloud.dialogflowcx_v3.services.versions.async_client import ( VersionsAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.versions.client import VersionsClient +from google.cloud.dialogflowcx_v3.services.webhooks.client import WebhooksClient from google.cloud.dialogflowcx_v3.services.webhooks.async_client import ( WebhooksAsyncClient, ) -from google.cloud.dialogflowcx_v3.services.webhooks.client import WebhooksClient + from google.cloud.dialogflowcx_v3.types.agent import Agent from google.cloud.dialogflowcx_v3.types.agent import AgentValidationResult from google.cloud.dialogflowcx_v3.types.agent import CreateAgentRequest @@ -85,15 +85,15 @@ from google.cloud.dialogflowcx_v3.types.agent import SpeechToTextSettings from google.cloud.dialogflowcx_v3.types.agent import UpdateAgentRequest from google.cloud.dialogflowcx_v3.types.agent import ValidateAgentRequest -from google.cloud.dialogflowcx_v3.types.audio_config import AudioEncoding from google.cloud.dialogflowcx_v3.types.audio_config import InputAudioConfig from google.cloud.dialogflowcx_v3.types.audio_config import OutputAudioConfig -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 SpeechWordInfo -from google.cloud.dialogflowcx_v3.types.audio_config import SsmlVoiceGender from google.cloud.dialogflowcx_v3.types.audio_config import SynthesizeSpeechConfig from google.cloud.dialogflowcx_v3.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflowcx_v3.types.audio_config import AudioEncoding +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.entity_type import CreateEntityTypeRequest from google.cloud.dialogflowcx_v3.types.entity_type import DeleteEntityTypeRequest from google.cloud.dialogflowcx_v3.types.entity_type import EntityType @@ -127,10 +127,14 @@ from google.cloud.dialogflowcx_v3.types.experiment import VersionVariants from google.cloud.dialogflowcx_v3.types.flow import CreateFlowRequest from google.cloud.dialogflowcx_v3.types.flow import DeleteFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ExportFlowResponse from google.cloud.dialogflowcx_v3.types.flow import Flow from google.cloud.dialogflowcx_v3.types.flow import FlowValidationResult from google.cloud.dialogflowcx_v3.types.flow import GetFlowRequest from google.cloud.dialogflowcx_v3.types.flow import GetFlowValidationResultRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowRequest +from google.cloud.dialogflowcx_v3.types.flow import ImportFlowResponse from google.cloud.dialogflowcx_v3.types.flow import ListFlowsRequest from google.cloud.dialogflowcx_v3.types.flow import ListFlowsResponse from google.cloud.dialogflowcx_v3.types.flow import NluSettings @@ -142,10 +146,10 @@ from google.cloud.dialogflowcx_v3.types.intent import DeleteIntentRequest from google.cloud.dialogflowcx_v3.types.intent import GetIntentRequest from google.cloud.dialogflowcx_v3.types.intent import Intent -from google.cloud.dialogflowcx_v3.types.intent import IntentView from google.cloud.dialogflowcx_v3.types.intent import ListIntentsRequest from google.cloud.dialogflowcx_v3.types.intent import ListIntentsResponse from google.cloud.dialogflowcx_v3.types.intent import UpdateIntentRequest +from google.cloud.dialogflowcx_v3.types.intent import IntentView from google.cloud.dialogflowcx_v3.types.page import CreatePageRequest from google.cloud.dialogflowcx_v3.types.page import DeletePageRequest from google.cloud.dialogflowcx_v3.types.page import EventHandler @@ -226,6 +230,7 @@ from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesRequest from google.cloud.dialogflowcx_v3.types.test_case import ExportTestCasesResponse from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import GetTestCaseResultRequest from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesMetadata from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesRequest from google.cloud.dialogflowcx_v3.types.test_case import ImportTestCasesResponse @@ -242,11 +247,11 @@ from google.cloud.dialogflowcx_v3.types.test_case import TestCaseResult from google.cloud.dialogflowcx_v3.types.test_case import TestConfig from google.cloud.dialogflowcx_v3.types.test_case import TestError -from google.cloud.dialogflowcx_v3.types.test_case import TestResult from google.cloud.dialogflowcx_v3.types.test_case import TestRunDifference from google.cloud.dialogflowcx_v3.types.test_case import TransitionCoverage from google.cloud.dialogflowcx_v3.types.test_case import TransitionRouteGroupCoverage from google.cloud.dialogflowcx_v3.types.test_case import UpdateTestCaseRequest +from google.cloud.dialogflowcx_v3.types.test_case import TestResult from google.cloud.dialogflowcx_v3.types.transition_route_group import ( CreateTransitionRouteGroupRequest, ) @@ -292,209 +297,214 @@ from google.cloud.dialogflowcx_v3.types.webhook import WebhookResponse __all__ = ( - "Agent", - "AgentValidationResult", - "AgentsAsyncClient", "AgentsClient", - "AudioEncoding", - "AudioInput", - "BatchDeleteTestCasesRequest", - "BatchRunTestCasesMetadata", - "BatchRunTestCasesRequest", - "BatchRunTestCasesResponse", - "CalculateCoverageRequest", - "CalculateCoverageResponse", - "ConversationTurn", - "CreateAgentRequest", - "CreateEntityTypeRequest", - "CreateEnvironmentRequest", - "CreateExperimentRequest", - "CreateFlowRequest", - "CreateIntentRequest", - "CreatePageRequest", - "CreateSecuritySettingsRequest", - "CreateSessionEntityTypeRequest", - "CreateTestCaseRequest", - "CreateTransitionRouteGroupRequest", - "CreateVersionOperationMetadata", - "CreateVersionRequest", - "CreateWebhookRequest", - "DeleteAgentRequest", - "DeleteEntityTypeRequest", - "DeleteEnvironmentRequest", - "DeleteExperimentRequest", - "DeleteFlowRequest", - "DeleteIntentRequest", - "DeletePageRequest", - "DeleteSecuritySettingsRequest", - "DeleteSessionEntityTypeRequest", - "DeleteTransitionRouteGroupRequest", - "DeleteVersionRequest", - "DeleteWebhookRequest", - "DetectIntentRequest", - "DetectIntentResponse", - "DtmfInput", - "EntityType", - "EntityTypesAsyncClient", + "AgentsAsyncClient", "EntityTypesClient", - "Environment", - "EnvironmentsAsyncClient", + "EntityTypesAsyncClient", "EnvironmentsClient", - "EventHandler", - "EventInput", - "Experiment", - "ExperimentsAsyncClient", + "EnvironmentsAsyncClient", "ExperimentsClient", + "ExperimentsAsyncClient", + "FlowsClient", + "FlowsAsyncClient", + "IntentsClient", + "IntentsAsyncClient", + "PagesClient", + "PagesAsyncClient", + "SecuritySettingsServiceClient", + "SecuritySettingsServiceAsyncClient", + "SessionEntityTypesClient", + "SessionEntityTypesAsyncClient", + "SessionsClient", + "SessionsAsyncClient", + "TestCasesClient", + "TestCasesAsyncClient", + "TransitionRouteGroupsClient", + "TransitionRouteGroupsAsyncClient", + "VersionsClient", + "VersionsAsyncClient", + "WebhooksClient", + "WebhooksAsyncClient", + "Agent", + "AgentValidationResult", + "CreateAgentRequest", + "DeleteAgentRequest", "ExportAgentRequest", "ExportAgentResponse", - "ExportTestCasesMetadata", - "ExportTestCasesRequest", - "ExportTestCasesResponse", - "Flow", - "FlowValidationResult", - "FlowsAsyncClient", - "FlowsClient", - "Form", - "FulfillIntentRequest", - "FulfillIntentResponse", - "Fulfillment", "GetAgentRequest", "GetAgentValidationResultRequest", - "GetEntityTypeRequest", - "GetEnvironmentRequest", - "GetExperimentRequest", - "GetFlowRequest", - "GetFlowValidationResultRequest", - "GetIntentRequest", - "GetPageRequest", - "GetSecuritySettingsRequest", - "GetSessionEntityTypeRequest", - "GetTestCaseRequest", - "GetTransitionRouteGroupRequest", - "GetVersionRequest", - "GetWebhookRequest", - "ImportTestCasesMetadata", - "ImportTestCasesRequest", - "ImportTestCasesResponse", - "InputAudioConfig", - "Intent", - "IntentCoverage", - "IntentInput", - "IntentView", - "IntentsAsyncClient", - "IntentsClient", "ListAgentsRequest", "ListAgentsResponse", + "RestoreAgentRequest", + "SpeechToTextSettings", + "UpdateAgentRequest", + "ValidateAgentRequest", + "InputAudioConfig", + "OutputAudioConfig", + "SpeechWordInfo", + "SynthesizeSpeechConfig", + "VoiceSelectionParams", + "AudioEncoding", + "OutputAudioEncoding", + "SpeechModelVariant", + "SsmlVoiceGender", + "CreateEntityTypeRequest", + "DeleteEntityTypeRequest", + "EntityType", + "GetEntityTypeRequest", "ListEntityTypesRequest", "ListEntityTypesResponse", + "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", + "Environment", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "LookupEnvironmentHistoryRequest", + "LookupEnvironmentHistoryResponse", + "UpdateEnvironmentRequest", + "CreateExperimentRequest", + "DeleteExperimentRequest", + "Experiment", + "GetExperimentRequest", "ListExperimentsRequest", "ListExperimentsResponse", + "StartExperimentRequest", + "StopExperimentRequest", + "UpdateExperimentRequest", + "VariantsHistory", + "VersionVariants", + "CreateFlowRequest", + "DeleteFlowRequest", + "ExportFlowRequest", + "ExportFlowResponse", + "Flow", + "FlowValidationResult", + "GetFlowRequest", + "GetFlowValidationResultRequest", + "ImportFlowRequest", + "ImportFlowResponse", "ListFlowsRequest", "ListFlowsResponse", + "NluSettings", + "TrainFlowRequest", + "UpdateFlowRequest", + "ValidateFlowRequest", + "Fulfillment", + "CreateIntentRequest", + "DeleteIntentRequest", + "GetIntentRequest", + "Intent", "ListIntentsRequest", "ListIntentsResponse", + "UpdateIntentRequest", + "IntentView", + "CreatePageRequest", + "DeletePageRequest", + "EventHandler", + "Form", + "GetPageRequest", "ListPagesRequest", "ListPagesResponse", + "Page", + "TransitionRoute", + "UpdatePageRequest", + "ResponseMessage", + "CreateSecuritySettingsRequest", + "DeleteSecuritySettingsRequest", + "GetSecuritySettingsRequest", "ListSecuritySettingsRequest", "ListSecuritySettingsResponse", - "ListSessionEntityTypesRequest", - "ListSessionEntityTypesResponse", - "ListTestCaseResultsRequest", - "ListTestCaseResultsResponse", - "ListTestCasesRequest", - "ListTestCasesResponse", - "ListTransitionRouteGroupsRequest", - "ListTransitionRouteGroupsResponse", - "ListVersionsRequest", - "ListVersionsResponse", - "ListWebhooksRequest", - "ListWebhooksResponse", - "LoadVersionRequest", - "LookupEnvironmentHistoryRequest", - "LookupEnvironmentHistoryResponse", + "SecuritySettings", + "UpdateSecuritySettingsRequest", + "AudioInput", + "DetectIntentRequest", + "DetectIntentResponse", + "DtmfInput", + "EventInput", + "FulfillIntentRequest", + "FulfillIntentResponse", + "IntentInput", "Match", "MatchIntentRequest", "MatchIntentResponse", - "NluSettings", - "OutputAudioConfig", - "OutputAudioEncoding", - "Page", - "PageInfo", - "PagesAsyncClient", - "PagesClient", "QueryInput", "QueryParameters", "QueryResult", - "ResourceName", - "ResponseMessage", - "RestoreAgentRequest", - "RunTestCaseMetadata", - "RunTestCaseRequest", - "RunTestCaseResponse", - "SecuritySettings", - "SecuritySettingsServiceAsyncClient", - "SecuritySettingsServiceClient", "SentimentAnalysisResult", - "SessionEntityType", - "SessionEntityTypesAsyncClient", - "SessionEntityTypesClient", - "SessionInfo", - "SessionsAsyncClient", - "SessionsClient", - "SpeechModelVariant", - "SpeechToTextSettings", - "SpeechWordInfo", - "SsmlVoiceGender", - "StartExperimentRequest", - "StopExperimentRequest", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", - "SynthesizeSpeechConfig", + "TextInput", + "CreateSessionEntityTypeRequest", + "DeleteSessionEntityTypeRequest", + "GetSessionEntityTypeRequest", + "ListSessionEntityTypesRequest", + "ListSessionEntityTypesResponse", + "SessionEntityType", + "UpdateSessionEntityTypeRequest", + "BatchDeleteTestCasesRequest", + "BatchRunTestCasesMetadata", + "BatchRunTestCasesRequest", + "BatchRunTestCasesResponse", + "CalculateCoverageRequest", + "CalculateCoverageResponse", + "ConversationTurn", + "CreateTestCaseRequest", + "ExportTestCasesMetadata", + "ExportTestCasesRequest", + "ExportTestCasesResponse", + "GetTestCaseRequest", + "GetTestCaseResultRequest", + "ImportTestCasesMetadata", + "ImportTestCasesRequest", + "ImportTestCasesResponse", + "IntentCoverage", + "ListTestCaseResultsRequest", + "ListTestCaseResultsResponse", + "ListTestCasesRequest", + "ListTestCasesResponse", + "RunTestCaseMetadata", + "RunTestCaseRequest", + "RunTestCaseResponse", "TestCase", "TestCaseError", "TestCaseResult", - "TestCasesAsyncClient", - "TestCasesClient", "TestConfig", "TestError", - "TestResult", "TestRunDifference", - "TextInput", - "TrainFlowRequest", "TransitionCoverage", - "TransitionRoute", - "TransitionRouteGroup", "TransitionRouteGroupCoverage", - "TransitionRouteGroupsAsyncClient", - "TransitionRouteGroupsClient", - "UpdateAgentRequest", - "UpdateEntityTypeRequest", - "UpdateEnvironmentRequest", - "UpdateExperimentRequest", - "UpdateFlowRequest", - "UpdateIntentRequest", - "UpdatePageRequest", - "UpdateSecuritySettingsRequest", - "UpdateSessionEntityTypeRequest", "UpdateTestCaseRequest", + "TestResult", + "CreateTransitionRouteGroupRequest", + "DeleteTransitionRouteGroupRequest", + "GetTransitionRouteGroupRequest", + "ListTransitionRouteGroupsRequest", + "ListTransitionRouteGroupsResponse", + "TransitionRouteGroup", "UpdateTransitionRouteGroupRequest", - "UpdateVersionRequest", - "UpdateWebhookRequest", - "ValidateAgentRequest", - "ValidateFlowRequest", + "ResourceName", "ValidationMessage", - "VariantsHistory", + "CreateVersionOperationMetadata", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "LoadVersionRequest", + "UpdateVersionRequest", "Version", - "VersionVariants", - "VersionsAsyncClient", - "VersionsClient", - "VoiceSelectionParams", + "CreateWebhookRequest", + "DeleteWebhookRequest", + "GetWebhookRequest", + "ListWebhooksRequest", + "ListWebhooksResponse", + "PageInfo", + "SessionInfo", + "UpdateWebhookRequest", "Webhook", "WebhookRequest", "WebhookResponse", - "WebhooksAsyncClient", - "WebhooksClient", ) diff --git a/google/cloud/dialogflowcx_v3/__init__.py b/google/cloud/dialogflowcx_v3/__init__.py index b85b6810..db4a67fb 100644 --- a/google/cloud/dialogflowcx_v3/__init__.py +++ b/google/cloud/dialogflowcx_v3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,19 +15,34 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient from .services.experiments import ExperimentsClient +from .services.experiments import ExperimentsAsyncClient from .services.flows import FlowsClient +from .services.flows import FlowsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.pages import PagesClient +from .services.pages import PagesAsyncClient from .services.security_settings_service import SecuritySettingsServiceClient +from .services.security_settings_service import SecuritySettingsServiceAsyncClient from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient from .services.test_cases import TestCasesClient +from .services.test_cases import TestCasesAsyncClient from .services.transition_route_groups import TransitionRouteGroupsClient +from .services.transition_route_groups import TransitionRouteGroupsAsyncClient from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient from .services.webhooks import WebhooksClient +from .services.webhooks import WebhooksAsyncClient + from .types.agent import Agent from .types.agent import AgentValidationResult from .types.agent import CreateAgentRequest @@ -43,15 +57,15 @@ from .types.agent import SpeechToTextSettings from .types.agent import UpdateAgentRequest from .types.agent import ValidateAgentRequest -from .types.audio_config import AudioEncoding from .types.audio_config import InputAudioConfig from .types.audio_config import OutputAudioConfig -from .types.audio_config import OutputAudioEncoding -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechWordInfo -from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender from .types.entity_type import CreateEntityTypeRequest from .types.entity_type import DeleteEntityTypeRequest from .types.entity_type import EntityType @@ -81,10 +95,14 @@ from .types.experiment import VersionVariants from .types.flow import CreateFlowRequest from .types.flow import DeleteFlowRequest +from .types.flow import ExportFlowRequest +from .types.flow import ExportFlowResponse from .types.flow import Flow from .types.flow import FlowValidationResult from .types.flow import GetFlowRequest from .types.flow import GetFlowValidationResultRequest +from .types.flow import ImportFlowRequest +from .types.flow import ImportFlowResponse from .types.flow import ListFlowsRequest from .types.flow import ListFlowsResponse from .types.flow import NluSettings @@ -96,10 +114,10 @@ from .types.intent import DeleteIntentRequest from .types.intent import GetIntentRequest from .types.intent import Intent -from .types.intent import IntentView from .types.intent import ListIntentsRequest from .types.intent import ListIntentsResponse from .types.intent import UpdateIntentRequest +from .types.intent import IntentView from .types.page import CreatePageRequest from .types.page import DeletePageRequest from .types.page import EventHandler @@ -156,6 +174,7 @@ from .types.test_case import ExportTestCasesRequest from .types.test_case import ExportTestCasesResponse from .types.test_case import GetTestCaseRequest +from .types.test_case import GetTestCaseResultRequest from .types.test_case import ImportTestCasesMetadata from .types.test_case import ImportTestCasesRequest from .types.test_case import ImportTestCasesResponse @@ -172,11 +191,11 @@ from .types.test_case import TestCaseResult from .types.test_case import TestConfig from .types.test_case import TestError -from .types.test_case import TestResult from .types.test_case import TestRunDifference from .types.test_case import TransitionCoverage from .types.test_case import TransitionRouteGroupCoverage from .types.test_case import UpdateTestCaseRequest +from .types.test_case import TestResult from .types.transition_route_group import CreateTransitionRouteGroupRequest from .types.transition_route_group import DeleteTransitionRouteGroupRequest from .types.transition_route_group import GetTransitionRouteGroupRequest @@ -207,8 +226,21 @@ from .types.webhook import WebhookRequest from .types.webhook import WebhookResponse - __all__ = ( + "AgentsAsyncClient", + "EntityTypesAsyncClient", + "EnvironmentsAsyncClient", + "ExperimentsAsyncClient", + "FlowsAsyncClient", + "IntentsAsyncClient", + "PagesAsyncClient", + "SecuritySettingsServiceAsyncClient", + "SessionEntityTypesAsyncClient", + "SessionsAsyncClient", + "TestCasesAsyncClient", + "TransitionRouteGroupsAsyncClient", + "VersionsAsyncClient", + "WebhooksAsyncClient", "Agent", "AgentValidationResult", "AgentsClient", @@ -260,6 +292,8 @@ "ExperimentsClient", "ExportAgentRequest", "ExportAgentResponse", + "ExportFlowRequest", + "ExportFlowResponse", "ExportTestCasesMetadata", "ExportTestCasesRequest", "ExportTestCasesResponse", @@ -282,9 +316,12 @@ "GetSecuritySettingsRequest", "GetSessionEntityTypeRequest", "GetTestCaseRequest", + "GetTestCaseResultRequest", "GetTransitionRouteGroupRequest", "GetVersionRequest", "GetWebhookRequest", + "ImportFlowRequest", + "ImportFlowResponse", "ImportTestCasesMetadata", "ImportTestCasesRequest", "ImportTestCasesResponse", diff --git a/google/cloud/dialogflowcx_v3/gapic_metadata.json b/google/cloud/dialogflowcx_v3/gapic_metadata.json new file mode 100644 index 00000000..6c6db5d4 --- /dev/null +++ b/google/cloud/dialogflowcx_v3/gapic_metadata.json @@ -0,0 +1,1095 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflowcx_v3", + "protoPackage": "google.cloud.dialogflow.cx.v3", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExperimentsAsyncClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FlowsAsyncClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "Pages": { + "clients": { + "grpc": { + "libraryClient": "PagesClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PagesAsyncClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + } + } + }, + "SecuritySettingsService": { + "clients": { + "grpc": { + "libraryClient": "SecuritySettingsServiceClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecuritySettingsServiceAsyncClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "TestCases": { + "clients": { + "grpc": { + "libraryClient": "TestCasesClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TestCasesAsyncClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + } + } + }, + "TransitionRouteGroups": { + "clients": { + "grpc": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TransitionRouteGroupsAsyncClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + }, + "Webhooks": { + "clients": { + "grpc": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebhooksAsyncClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/dialogflowcx_v3/services/__init__.py b/google/cloud/dialogflowcx_v3/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/dialogflowcx_v3/services/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/dialogflowcx_v3/services/agents/__init__.py b/google/cloud/dialogflowcx_v3/services/agents/__init__.py index 4bcbd7ac..0501fa94 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/agents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AgentsClient from .async_client import AgentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/agents/async_client.py b/google/cloud/dialogflowcx_v3/services/agents/async_client.py index 2dcd732c..60e08061 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/agents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,10 +32,9 @@ from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport from .client import AgentsClient @@ -59,6 +56,8 @@ class AgentsAsyncClient: parse_agent_validation_result_path = staticmethod( AgentsClient.parse_agent_validation_result_path ) + environment_path = staticmethod(AgentsClient.environment_path) + parse_environment_path = staticmethod(AgentsClient.parse_environment_path) flow_path = staticmethod(AgentsClient.flow_path) parse_flow_path = staticmethod(AgentsClient.parse_flow_path) flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) @@ -69,29 +68,25 @@ class AgentsAsyncClient: parse_security_settings_path = staticmethod( AgentsClient.parse_security_settings_path ) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( AgentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AgentsClient.common_folder_path) parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) parse_common_organization_path = staticmethod( AgentsClient.parse_common_organization_path ) - common_project_path = staticmethod(AgentsClient.common_project_path) parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) parse_common_location_path = staticmethod(AgentsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -106,7 +101,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -123,7 +118,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AgentsTransport: The transport used by the client instance. @@ -137,12 +132,12 @@ def transport(self) -> AgentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AgentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +169,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -205,7 +199,6 @@ async def list_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. @@ -235,7 +228,6 @@ async def list_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -287,7 +279,6 @@ async def get_agent( 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. @@ -326,7 +317,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -378,7 +368,6 @@ async def create_agent( This corresponds to the ``agent`` 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. @@ -417,7 +406,6 @@ async def create_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if agent is not None: @@ -448,7 +436,7 @@ async def update_agent( request: gcdc_agent.UpdateAgentRequest = None, *, agent: gcdc_agent.Agent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -472,7 +460,6 @@ async def update_agent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -511,7 +498,6 @@ async def update_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent if update_mask is not None: @@ -561,7 +547,6 @@ async def delete_agent( 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. @@ -582,7 +567,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -619,7 +603,6 @@ async def export_agent( request (:class:`google.cloud.dialogflowcx_v3.types.ExportAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -637,7 +620,6 @@ async def export_agent( """ # Create or coerce a protobuf request object. - request = agent.ExportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -662,7 +644,7 @@ async def export_agent( response, self._client._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -685,7 +667,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflowcx_v3.types.RestoreAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -712,7 +693,6 @@ async def restore_agent( """ # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -736,8 +716,8 @@ async def restore_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -760,7 +740,6 @@ async def validate_agent( request (:class:`google.cloud.dialogflowcx_v3.types.ValidateAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -774,7 +753,6 @@ async def validate_agent( """ # Create or coerce a protobuf request object. - request = agent.ValidateAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -820,7 +798,6 @@ async def get_agent_validation_result( 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. @@ -847,7 +824,6 @@ async def get_agent_validation_result( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/agents/client.py b/google/cloud/dialogflowcx_v3/services/agents/client.py index 8ebc02b7..61cbe72c 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/client.py +++ b/google/cloud/dialogflowcx_v3/services/agents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,10 +36,9 @@ from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AgentsGrpcTransport from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class AgentsClientMeta(type): _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AgentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class AgentsClient(metaclass=AgentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AgentsTransport: The transport used by the client instance. + AgentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path, @@ -178,30 +178,48 @@ def parse_agent_path(path: str) -> Dict[str, str]: @staticmethod def agent_validation_result_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent_validation_result string.""" + """Returns a fully-qualified agent_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_validation_result_path(path: str) -> Dict[str, str]: - """Parse a agent_validation_result path into its component segments.""" + """Parses a agent_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path, ) return m.groupdict() if m else {} + @staticmethod + def environment_path( + project: str, location: str, agent: str, environment: str, + ) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( + project=project, location=location, agent=agent, environment=environment, + ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str, str]: + """Parses a environment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -212,14 +230,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: def flow_validation_result_path( project: str, location: str, agent: str, flow: str, ) -> str: - """Return a fully-qualified flow_validation_result string.""" + """Returns a fully-qualified flow_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_validation_result_path(path: str) -> Dict[str, str]: - """Parse a flow_validation_result path into its component segments.""" + """Parses a flow_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path, @@ -230,14 +248,14 @@ def parse_flow_validation_result_path(path: str) -> Dict[str, str]: def security_settings_path( project: str, location: str, security_settings: str, ) -> str: - """Return a fully-qualified security_settings string.""" + """Returns a fully-qualified security_settings string.""" return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @staticmethod def parse_security_settings_path(path: str) -> Dict[str, str]: - """Parse a security_settings path into its component segments.""" + """Parses a security_settings path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path, @@ -246,7 +264,7 @@ def parse_security_settings_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -259,7 +277,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -270,7 +288,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -281,7 +299,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -292,7 +310,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -306,12 +324,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AgentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -366,9 +384,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -380,12 +399,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -400,8 +421,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -439,7 +460,6 @@ def list_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. @@ -471,10 +491,8 @@ def list_agents( # there are no flattened fields. if not isinstance(request, agent.ListAgentsRequest): request = agent.ListAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -522,7 +540,6 @@ def get_agent( 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. @@ -563,10 +580,8 @@ def get_agent( # there are no flattened fields. if not isinstance(request, agent.GetAgentRequest): request = agent.GetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -614,7 +629,6 @@ def create_agent( This corresponds to the ``agent`` 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. @@ -655,10 +669,8 @@ def create_agent( # there are no flattened fields. if not isinstance(request, gcdc_agent.CreateAgentRequest): request = gcdc_agent.CreateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if agent is not None: @@ -685,7 +697,7 @@ def update_agent( request: gcdc_agent.UpdateAgentRequest = None, *, agent: gcdc_agent.Agent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -709,7 +721,6 @@ def update_agent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -750,10 +761,8 @@ def update_agent( # there are no flattened fields. if not isinstance(request, gcdc_agent.UpdateAgentRequest): request = gcdc_agent.UpdateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent if update_mask is not None: @@ -799,7 +808,6 @@ def delete_agent( 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. @@ -822,10 +830,8 @@ def delete_agent( # there are no flattened fields. if not isinstance(request, agent.DeleteAgentRequest): request = agent.DeleteAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -858,7 +864,6 @@ def export_agent( request (google.cloud.dialogflowcx_v3.types.ExportAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -876,7 +881,6 @@ def export_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ExportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -902,7 +906,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -925,7 +929,6 @@ def restore_agent( request (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -952,7 +955,6 @@ def restore_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.RestoreAgentRequest. # There's no risk of modifying the input as we've already verified @@ -977,8 +979,8 @@ def restore_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1001,7 +1003,6 @@ def validate_agent( request (google.cloud.dialogflowcx_v3.types.ValidateAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1015,7 +1016,6 @@ def validate_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ValidateAgentRequest. # There's no risk of modifying the input as we've already verified @@ -1062,7 +1062,6 @@ def get_agent_validation_result( 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. @@ -1091,10 +1090,8 @@ def get_agent_validation_result( # there are no flattened fields. if not isinstance(request, agent.GetAgentValidationResultRequest): request = agent.GetAgentValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/agents/pagers.py b/google/cloud/dialogflowcx_v3/services/agents/pagers.py index f937cd89..02563cca 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/agents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py index dfed9192..ceadcd3a 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/agents/transports/base.py b/google/cloud/dialogflowcx_v3/services/agents/transports/base.py index e313f4de..8fafde41 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -50,21 +60,24 @@ class AgentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -152,87 +212,77 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ListAgentsRequest], - typing.Union[ - agent.ListAgentsResponse, typing.Awaitable[agent.ListAgentsResponse] - ], + Union[agent.ListAgentsResponse, Awaitable[agent.ListAgentsResponse]], ]: raise NotImplementedError() @property def get_agent( self, - ) -> typing.Callable[ - [agent.GetAgentRequest], - typing.Union[agent.Agent, typing.Awaitable[agent.Agent]], - ]: + ) -> Callable[[agent.GetAgentRequest], Union[agent.Agent, Awaitable[agent.Agent]]]: raise NotImplementedError() @property def create_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_agent.CreateAgentRequest], - typing.Union[gcdc_agent.Agent, typing.Awaitable[gcdc_agent.Agent]], + Union[gcdc_agent.Agent, Awaitable[gcdc_agent.Agent]], ]: raise NotImplementedError() @property def update_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_agent.UpdateAgentRequest], - typing.Union[gcdc_agent.Agent, typing.Awaitable[gcdc_agent.Agent]], + Union[gcdc_agent.Agent, Awaitable[gcdc_agent.Agent]], ]: raise NotImplementedError() @property def delete_agent( self, - ) -> typing.Callable[ - [agent.DeleteAgentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [agent.DeleteAgentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def export_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ExportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def restore_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.RestoreAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def validate_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ValidateAgentRequest], - typing.Union[ - agent.AgentValidationResult, typing.Awaitable[agent.AgentValidationResult] - ], + Union[agent.AgentValidationResult, Awaitable[agent.AgentValidationResult]], ]: raise NotImplementedError() @property def get_agent_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetAgentValidationResultRequest], - typing.Union[ - agent.AgentValidationResult, typing.Awaitable[agent.AgentValidationResult] - ], + Union[agent.AgentValidationResult, Awaitable[agent.AgentValidationResult]], ]: 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 1522556d..99a98b9e 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -110,7 +108,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -118,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,24 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -371,7 +344,7 @@ def update_agent( return self._stubs["update_agent"] @property - def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: + def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty_pb2.Empty]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -390,14 +363,14 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ExportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a binary file. @@ -416,14 +389,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], operations.Operation]: + ) -> Callable[[agent.RestoreAgentRequest], operations_pb2.Operation]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a binary file. @@ -445,7 +418,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] 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 30d00bd9..a7b09070 100644 --- a/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/agents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO from .grpc import AgentsGrpcTransport @@ -57,7 +54,7 @@ class AgentsGrpcAsyncIOTransport(AgentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -65,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -143,10 +143,10 @@ def __init__( 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 + 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: @@ -155,7 +155,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -163,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -379,7 +351,7 @@ def update_agent( @property def delete_agent( self, - ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -398,14 +370,14 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a binary file. @@ -424,14 +396,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a binary file. @@ -453,7 +425,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py b/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py index f52849c6..77cd53e9 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EntityTypesClient from .async_client import EntityTypesAsyncClient 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 f74b07c0..8ee7d941 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -50,27 +47,22 @@ class EntityTypesAsyncClient: entity_type_path = staticmethod(EntityTypesClient.entity_type_path) parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) - common_billing_account_path = staticmethod( EntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) - common_organization_path = staticmethod(EntityTypesClient.common_organization_path) parse_common_organization_path = staticmethod( EntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(EntityTypesClient.common_project_path) parse_common_project_path = staticmethod( EntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(EntityTypesClient.common_location_path) parse_common_location_path = staticmethod( EntityTypesClient.parse_common_location_path @@ -78,7 +70,8 @@ class EntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -93,7 +86,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -110,7 +103,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EntityTypesTransport: The transport used by the client instance. @@ -124,12 +117,12 @@ def transport(self) -> EntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -161,7 +154,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -193,7 +185,6 @@ async def list_entity_types( 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. @@ -223,7 +214,6 @@ async def list_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -275,7 +265,6 @@ async def get_entity_type( 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. @@ -334,7 +323,6 @@ async def get_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -386,7 +374,6 @@ async def create_entity_type( This corresponds to the ``entity_type`` 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. @@ -445,7 +432,6 @@ async def create_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -476,7 +462,7 @@ async def update_entity_type( request: gcdc_entity_type.UpdateEntityTypeRequest = None, *, entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -499,7 +485,6 @@ async def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -558,7 +543,6 @@ async def update_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if update_mask is not None: @@ -608,7 +592,6 @@ async def delete_entity_type( 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. @@ -629,7 +612,6 @@ async def delete_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/client.py b/google/cloud/dialogflowcx_v3/services/entity_types/client.py index 852b3ef4..6f12cfb0 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/client.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,8 +33,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class EntityTypesClientMeta(type): _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class EntityTypesClient(metaclass=EntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,10 +149,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EntityTypesTransport: The transport used by the client instance. + EntityTypesTransport: The transport used by the client + instance. """ return self._transport @@ -161,14 +161,14 @@ def transport(self) -> EntityTypesTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -177,7 +177,7 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -190,7 +190,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -201,7 +201,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -237,12 +237,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -297,9 +297,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -311,12 +312,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -331,8 +334,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -371,7 +374,6 @@ def list_entity_types( 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. @@ -403,10 +405,8 @@ def list_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.ListEntityTypesRequest): request = entity_type.ListEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -454,7 +454,6 @@ def get_entity_type( 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. @@ -515,10 +514,8 @@ def get_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.GetEntityTypeRequest): request = entity_type.GetEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -566,7 +563,6 @@ def create_entity_type( This corresponds to the ``entity_type`` 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. @@ -627,10 +623,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcdc_entity_type.CreateEntityTypeRequest): request = gcdc_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -657,7 +651,7 @@ def update_entity_type( request: gcdc_entity_type.UpdateEntityTypeRequest = None, *, entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -680,7 +674,6 @@ def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -741,10 +734,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcdc_entity_type.UpdateEntityTypeRequest): request = gcdc_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if update_mask is not None: @@ -790,7 +781,6 @@ def delete_entity_type( 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. @@ -813,10 +803,8 @@ def delete_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.DeleteEntityTypeRequest): request = entity_type.DeleteEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py b/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py index 5a575953..25fa1a0f 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py index 963959d1..07ea82e1 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 e3faf53a..edd3e613 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -48,21 +58,24 @@ class EntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,11 +191,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.ListEntityTypesRequest], - typing.Union[ + Union[ entity_type.ListEntityTypesResponse, - typing.Awaitable[entity_type.ListEntityTypesResponse], + Awaitable[entity_type.ListEntityTypesResponse], ], ]: raise NotImplementedError() @@ -143,40 +203,36 @@ def list_entity_types( @property def get_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.GetEntityTypeRequest], - typing.Union[entity_type.EntityType, typing.Awaitable[entity_type.EntityType]], + Union[entity_type.EntityType, Awaitable[entity_type.EntityType]], ]: raise NotImplementedError() @property def create_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcdc_entity_type.EntityType, typing.Awaitable[gcdc_entity_type.EntityType] - ], + Union[gcdc_entity_type.EntityType, Awaitable[gcdc_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcdc_entity_type.EntityType, typing.Awaitable[gcdc_entity_type.EntityType] - ], + Union[gcdc_entity_type.EntityType, Awaitable[gcdc_entity_type.EntityType]], ]: raise NotImplementedError() @property def delete_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.DeleteEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py index 24b05efe..f4fe8095 100644 --- a/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -365,7 +338,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty.Empty]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty_pb2.Empty]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -384,7 +357,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] 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 210f2c7f..38cec4de 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import entity_type from google.cloud.dialogflowcx_v3.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -56,7 +53,7 @@ class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -374,7 +346,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty.Empty]]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -393,7 +365,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] diff --git a/google/cloud/dialogflowcx_v3/services/environments/__init__.py b/google/cloud/dialogflowcx_v3/services/environments/__init__.py index a67f2316..0c2be948 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/environments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EnvironmentsClient from .async_client import EnvironmentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/environments/async_client.py b/google/cloud/dialogflowcx_v3/services/environments/async_client.py index 542ce93b..c14978ad 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/environments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,10 +31,9 @@ from google.cloud.dialogflowcx_v3.services.environments import pagers from google.cloud.dialogflowcx_v3.types import environment from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport from .client import EnvironmentsClient @@ -56,27 +53,22 @@ class EnvironmentsAsyncClient: parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) version_path = staticmethod(EnvironmentsClient.version_path) parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod( EnvironmentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EnvironmentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) parse_common_organization_path = staticmethod( EnvironmentsClient.parse_common_organization_path ) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) parse_common_project_path = staticmethod( EnvironmentsClient.parse_common_project_path ) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) parse_common_location_path = staticmethod( EnvironmentsClient.parse_common_location_path @@ -84,7 +76,8 @@ class EnvironmentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EnvironmentsTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> EnvironmentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -200,7 +192,6 @@ async def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -230,7 +221,6 @@ async def list_environments( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -285,7 +275,6 @@ async def get_environment( 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. @@ -325,7 +314,6 @@ async def get_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -383,7 +371,6 @@ async def create_environment( This corresponds to the ``environment`` 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. @@ -421,7 +408,6 @@ async def create_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if environment is not None: @@ -449,7 +435,7 @@ async def create_environment( response, self._client._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -460,7 +446,7 @@ async def update_environment( request: gcdc_environment.UpdateEnvironmentRequest = None, *, environment: gcdc_environment.Environment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -484,7 +470,6 @@ async def update_environment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -522,7 +507,6 @@ async def update_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if environment is not None: request.environment = environment if update_mask is not None: @@ -552,7 +536,7 @@ async def update_environment( response, self._client._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -583,7 +567,6 @@ async def delete_environment( 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. @@ -604,7 +587,6 @@ async def delete_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -651,7 +633,6 @@ async def lookup_environment_history( 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. @@ -681,7 +662,6 @@ async def lookup_environment_history( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/environments/client.py b/google/cloud/dialogflowcx_v3/services/environments/client.py index 31600a28..b730a77d 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3/services/environments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,10 +35,9 @@ from google.cloud.dialogflowcx_v3.services.environments import pagers from google.cloud.dialogflowcx_v3.types import environment from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EnvironmentsGrpcTransport from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class EnvironmentsClientMeta(type): _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EnvironmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class EnvironmentsClient(metaclass=EnvironmentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,10 +153,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EnvironmentsTransport: The transport used by the client instance. + EnvironmentsTransport: The transport used by the client + instance. """ return self._transport @@ -165,14 +165,14 @@ def transport(self) -> EnvironmentsTransport: def environment_path( project: str, location: str, agent: str, environment: str, ) -> str: - """Return a fully-qualified environment string.""" + """Returns a fully-qualified environment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @staticmethod def parse_environment_path(path: str) -> Dict[str, str]: - """Parse a environment path into its component segments.""" + """Parses a environment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_environment_path(path: str) -> Dict[str, str]: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -212,7 +212,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -245,7 +245,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -259,12 +259,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EnvironmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -333,12 +334,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -353,8 +356,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -394,7 +397,6 @@ def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -426,10 +428,8 @@ def list_environments( # there are no flattened fields. if not isinstance(request, environment.ListEnvironmentsRequest): request = environment.ListEnvironmentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -480,7 +480,6 @@ def get_environment( 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. @@ -522,10 +521,8 @@ def get_environment( # there are no flattened fields. if not isinstance(request, environment.GetEnvironmentRequest): request = environment.GetEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -579,7 +576,6 @@ def create_environment( This corresponds to the ``environment`` 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. @@ -619,10 +615,8 @@ def create_environment( # there are no flattened fields. if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): request = gcdc_environment.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if environment is not None: @@ -646,7 +640,7 @@ def create_environment( response, self._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -657,7 +651,7 @@ def update_environment( request: gcdc_environment.UpdateEnvironmentRequest = None, *, environment: gcdc_environment.Environment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -681,7 +675,6 @@ def update_environment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -721,10 +714,8 @@ def update_environment( # there are no flattened fields. if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): request = gcdc_environment.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if environment is not None: request.environment = environment if update_mask is not None: @@ -750,7 +741,7 @@ def update_environment( response, self._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -781,7 +772,6 @@ def delete_environment( 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. @@ -804,10 +794,8 @@ def delete_environment( # there are no flattened fields. if not isinstance(request, environment.DeleteEnvironmentRequest): request = environment.DeleteEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -850,7 +838,6 @@ def lookup_environment_history( 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. @@ -882,10 +869,8 @@ def lookup_environment_history( # there are no flattened fields. if not isinstance(request, environment.LookupEnvironmentHistoryRequest): request = environment.LookupEnvironmentHistoryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/environments/pagers.py b/google/cloud/dialogflowcx_v3/services/environments/pagers.py index 04e1b444..bf98c8b6 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/environments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py index aff44bcd..c72efee4 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3/services/environments/transports/base.py index 7f827332..ec2e7970 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore 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 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -50,21 +60,24 @@ class EnvironmentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], ], ]: raise NotImplementedError() @@ -155,49 +215,47 @@ def list_environments( @property def get_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.GetEnvironmentRequest], - typing.Union[ - environment.Environment, typing.Awaitable[environment.Environment] - ], + Union[environment.Environment, Awaitable[environment.Environment]], ]: raise NotImplementedError() @property def create_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_environment.CreateEnvironmentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_environment.UpdateEnvironmentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.DeleteEnvironmentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def lookup_environment_history( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.LookupEnvironmentHistoryRequest], - typing.Union[ + Union[ environment.LookupEnvironmentHistoryResponse, - typing.Awaitable[environment.LookupEnvironmentHistoryResponse], + Awaitable[environment.LookupEnvironmentHistoryResponse], ], ]: 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 e73d51a4..e513c28f 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 environment from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -327,7 +300,9 @@ def get_environment( @property def create_environment( self, - ) -> Callable[[gcdc_environment.CreateEnvironmentRequest], operations.Operation]: + ) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], operations_pb2.Operation + ]: r"""Return a callable for the create environment method over gRPC. Creates an @@ -348,14 +323,16 @@ def create_environment( self._stubs["create_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment", request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_environment"] @property def update_environment( self, - ) -> Callable[[gcdc_environment.UpdateEnvironmentRequest], operations.Operation]: + ) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], operations_pb2.Operation + ]: r"""Return a callable for the update environment method over gRPC. Updates the specified @@ -375,14 +352,14 @@ def update_environment( self._stubs["update_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment", request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_environment"] @property def delete_environment( self, - ) -> Callable[[environment.DeleteEnvironmentRequest], empty.Empty]: + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: r"""Return a callable for the delete environment method over gRPC. Deletes the specified @@ -402,7 +379,7 @@ def delete_environment( self._stubs["delete_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/DeleteEnvironment", request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_environment"] 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 b3b671e0..71c2c645 100644 --- a/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/environments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import environment from google.cloud.dialogflowcx_v3.types import environment as gcdc_environment -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -58,7 +55,7 @@ class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -337,7 +309,7 @@ def get_environment( def create_environment( self, ) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], Awaitable[operations.Operation] + [gcdc_environment.CreateEnvironmentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create environment method over gRPC. @@ -359,7 +331,7 @@ def create_environment( self._stubs["create_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/CreateEnvironment", request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_environment"] @@ -367,7 +339,7 @@ def create_environment( def update_environment( self, ) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], Awaitable[operations.Operation] + [gcdc_environment.UpdateEnvironmentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update environment method over gRPC. @@ -388,14 +360,14 @@ def update_environment( self._stubs["update_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/UpdateEnvironment", request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_environment"] @property def delete_environment( self, - ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete environment method over gRPC. Deletes the specified @@ -415,7 +387,7 @@ def delete_environment( self._stubs["delete_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Environments/DeleteEnvironment", request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_environment"] diff --git a/google/cloud/dialogflowcx_v3/services/experiments/__init__.py b/google/cloud/dialogflowcx_v3/services/experiments/__init__.py index c9141d08..560b13da 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ExperimentsClient from .async_client import ExperimentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py index 045685d2..b91f983e 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,19 +20,18 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.experiments import pagers from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport from .client import ExperimentsClient @@ -54,27 +51,22 @@ class ExperimentsAsyncClient: parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) version_path = staticmethod(ExperimentsClient.version_path) parse_version_path = staticmethod(ExperimentsClient.parse_version_path) - common_billing_account_path = staticmethod( ExperimentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ExperimentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ExperimentsClient.common_folder_path) parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExperimentsClient.common_organization_path) parse_common_organization_path = staticmethod( ExperimentsClient.parse_common_organization_path ) - common_project_path = staticmethod(ExperimentsClient.common_project_path) parse_common_project_path = staticmethod( ExperimentsClient.parse_common_project_path ) - common_location_path = staticmethod(ExperimentsClient.common_location_path) parse_common_location_path = staticmethod( ExperimentsClient.parse_common_location_path @@ -82,7 +74,8 @@ class ExperimentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +90,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -114,7 +107,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ExperimentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ExperimentsTransport: The transport used by the client instance. @@ -128,12 +121,12 @@ def transport(self) -> ExperimentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ExperimentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the experiments client. + """Instantiates the experiments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -165,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ExperimentsClient( credentials=credentials, transport=transport, @@ -198,7 +190,6 @@ async def list_experiments( 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. @@ -228,7 +219,6 @@ async def list_experiments( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -283,7 +273,6 @@ async def get_experiment( 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. @@ -310,7 +299,6 @@ async def get_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -369,7 +357,6 @@ async def create_experiment( This corresponds to the ``experiment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -396,7 +383,6 @@ async def create_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if experiment is not None: @@ -427,7 +413,7 @@ async def update_experiment( request: gcdc_experiment.UpdateExperimentRequest = None, *, experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -451,7 +437,6 @@ async def update_experiment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -478,7 +463,6 @@ async def update_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if experiment is not None: request.experiment = experiment if update_mask is not None: @@ -531,7 +515,6 @@ async def delete_experiment( 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. @@ -552,7 +535,6 @@ async def delete_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -600,7 +582,6 @@ async def start_experiment( 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. @@ -627,7 +608,6 @@ async def start_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -676,7 +656,6 @@ async def stop_experiment( 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. @@ -703,7 +682,6 @@ async def stop_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/experiments/client.py b/google/cloud/dialogflowcx_v3/services/experiments/client.py index 2b3e5ea4..b95a78b3 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/client.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,10 +33,9 @@ from google.cloud.dialogflowcx_v3.services.experiments import pagers from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentsGrpcTransport from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class ExperimentsClientMeta(type): _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ExperimentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class ExperimentsClient(metaclass=ExperimentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,10 +151,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ExperimentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ExperimentsTransport: The transport used by the client instance. + ExperimentsTransport: The transport used by the client + instance. """ return self._transport @@ -163,7 +163,7 @@ def transport(self) -> ExperimentsTransport: def experiment_path( project: str, location: str, agent: str, environment: str, experiment: str, ) -> str: - """Return a fully-qualified experiment string.""" + """Returns a fully-qualified experiment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( project=project, location=location, @@ -174,7 +174,7 @@ def experiment_path( @staticmethod def parse_experiment_path(path: str) -> Dict[str, str]: - """Parse a experiment path into its component segments.""" + """Parses a experiment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path, @@ -185,14 +185,14 @@ def parse_experiment_path(path: str) -> Dict[str, str]: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -201,7 +201,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -214,7 +214,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -225,7 +225,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -236,7 +236,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -247,7 +247,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -261,12 +261,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ExperimentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the experiments client. + """Instantiates the experiments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -321,9 +321,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -335,12 +336,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -355,8 +358,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -396,7 +399,6 @@ def list_experiments( 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. @@ -428,10 +430,8 @@ def list_experiments( # there are no flattened fields. if not isinstance(request, experiment.ListExperimentsRequest): request = experiment.ListExperimentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -482,7 +482,6 @@ def get_experiment( 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. @@ -511,10 +510,8 @@ def get_experiment( # there are no flattened fields. if not isinstance(request, experiment.GetExperimentRequest): request = experiment.GetExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -569,7 +566,6 @@ def create_experiment( This corresponds to the ``experiment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -598,10 +594,8 @@ def create_experiment( # there are no flattened fields. if not isinstance(request, gcdc_experiment.CreateExperimentRequest): request = gcdc_experiment.CreateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if experiment is not None: @@ -628,7 +622,7 @@ def update_experiment( request: gcdc_experiment.UpdateExperimentRequest = None, *, experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -652,7 +646,6 @@ def update_experiment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -681,10 +674,8 @@ def update_experiment( # there are no flattened fields. if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): request = gcdc_experiment.UpdateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if experiment is not None: request.experiment = experiment if update_mask is not None: @@ -733,7 +724,6 @@ def delete_experiment( 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. @@ -756,10 +746,8 @@ def delete_experiment( # there are no flattened fields. if not isinstance(request, experiment.DeleteExperimentRequest): request = experiment.DeleteExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -803,7 +791,6 @@ def start_experiment( 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. @@ -832,10 +819,8 @@ def start_experiment( # there are no flattened fields. if not isinstance(request, experiment.StartExperimentRequest): request = experiment.StartExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -880,7 +865,6 @@ def stop_experiment( 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. @@ -909,10 +893,8 @@ def stop_experiment( # there are no flattened fields. if not isinstance(request, experiment.StopExperimentRequest): request = experiment.StopExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/experiments/pagers.py b/google/cloud/dialogflowcx_v3/services/experiments/pagers.py index dbac2527..a9041fe5 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py index d1972e23..3be44737 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py index a476c814..afba41e2 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ExperimentsTransport(abc.ABC): """Abstract transport class for Experiments.""" @@ -48,21 +58,24 @@ class ExperimentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -137,11 +197,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_experiments( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.ListExperimentsRequest], - typing.Union[ + Union[ experiment.ListExperimentsResponse, - typing.Awaitable[experiment.ListExperimentsResponse], + Awaitable[experiment.ListExperimentsResponse], ], ]: raise NotImplementedError() @@ -149,58 +209,54 @@ def list_experiments( @property def get_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.GetExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() @property def create_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_experiment.CreateExperimentRequest], - typing.Union[ - gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] - ], + Union[gcdc_experiment.Experiment, Awaitable[gcdc_experiment.Experiment]], ]: raise NotImplementedError() @property def update_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_experiment.UpdateExperimentRequest], - typing.Union[ - gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] - ], + Union[gcdc_experiment.Experiment, Awaitable[gcdc_experiment.Experiment]], ]: raise NotImplementedError() @property def delete_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.DeleteExperimentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def start_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.StartExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() @property def stop_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.StopExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py index 369bbd4c..f1deea19 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -370,7 +343,7 @@ def update_experiment( @property def delete_experiment( self, - ) -> Callable[[experiment.DeleteExperimentRequest], empty.Empty]: + ) -> Callable[[experiment.DeleteExperimentRequest], empty_pb2.Empty]: r"""Return a callable for the delete experiment method over gRPC. Deletes the specified @@ -390,7 +363,7 @@ def delete_experiment( self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment", request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_experiment"] 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 237cc21c..2ce07e07 100644 --- a/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/experiments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import experiment from google.cloud.dialogflowcx_v3.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .grpc import ExperimentsGrpcTransport @@ -56,7 +53,7 @@ class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -375,7 +347,7 @@ def update_experiment( @property def delete_experiment( self, - ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete experiment method over gRPC. Deletes the specified @@ -395,7 +367,7 @@ def delete_experiment( self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Experiments/DeleteExperiment", request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_experiment"] diff --git a/google/cloud/dialogflowcx_v3/services/flows/__init__.py b/google/cloud/dialogflowcx_v3/services/flows/__init__.py index edf52773..03ec82a2 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/flows/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import FlowsClient from .async_client import FlowsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/flows/async_client.py b/google/cloud/dialogflowcx_v3/services/flows/async_client.py index e0235fe8..6815a427 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/flows/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -35,11 +33,10 @@ from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport from .client import FlowsClient @@ -63,31 +60,31 @@ class FlowsAsyncClient: parse_intent_path = staticmethod(FlowsClient.parse_intent_path) page_path = staticmethod(FlowsClient.page_path) parse_page_path = staticmethod(FlowsClient.parse_page_path) + transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod( + FlowsClient.parse_transition_route_group_path + ) webhook_path = staticmethod(FlowsClient.webhook_path) parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) - common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( FlowsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(FlowsClient.common_folder_path) parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) - common_organization_path = staticmethod(FlowsClient.common_organization_path) parse_common_organization_path = staticmethod( FlowsClient.parse_common_organization_path ) - common_project_path = staticmethod(FlowsClient.common_project_path) parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) - common_location_path = staticmethod(FlowsClient.common_location_path) parse_common_location_path = staticmethod(FlowsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -102,7 +99,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -119,7 +116,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FlowsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: FlowsTransport: The transport used by the client instance. @@ -133,12 +130,12 @@ def transport(self) -> FlowsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, FlowsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the flows client. + """Instantiates the flows client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -170,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = FlowsClient( credentials=credentials, transport=transport, @@ -206,7 +202,6 @@ async def create_flow( This corresponds to the ``flow`` 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. @@ -254,7 +249,6 @@ async def create_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if flow is not None: @@ -302,7 +296,6 @@ async def delete_flow( 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. @@ -323,7 +316,6 @@ async def delete_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -368,7 +360,6 @@ async def list_flows( 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. @@ -398,7 +389,6 @@ async def list_flows( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -450,7 +440,6 @@ async def get_flow( 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. @@ -498,7 +487,6 @@ async def get_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -527,7 +515,7 @@ async def update_flow( request: gcdc_flow.UpdateFlowRequest = None, *, flow: gcdc_flow.Flow = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -551,7 +539,6 @@ async def update_flow( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -599,7 +586,6 @@ async def update_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if flow is not None: request.flow = flow if update_mask is not None: @@ -650,7 +636,6 @@ async def train_flow( 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. @@ -690,7 +675,6 @@ async def train_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -715,8 +699,8 @@ async def train_flow( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -739,7 +723,6 @@ async def validate_flow( request (:class:`google.cloud.dialogflowcx_v3.types.ValidateFlowRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -753,7 +736,6 @@ async def validate_flow( """ # Create or coerce a protobuf request object. - request = flow.ValidateFlowRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -799,7 +781,6 @@ async def get_flow_validation_result( 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. @@ -826,7 +807,6 @@ async def get_flow_validation_result( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -850,6 +830,131 @@ async def get_flow_validation_result( # Done; return the response. return response + async def import_flow( + self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ImportFlowRequest`): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_flow( + self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (:class:`google.cloud.dialogflowcx_v3.types.ExportFlowRequest`): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3/services/flows/client.py b/google/cloud/dialogflowcx_v3/services/flows/client.py index 6abaac84..dd6bbebf 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/client.py +++ b/google/cloud/dialogflowcx_v3/services/flows/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -39,11 +37,10 @@ from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FlowsGrpcTransport from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class FlowsClientMeta(type): _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[FlowsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +82,8 @@ class FlowsClient(metaclass=FlowsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -119,7 +117,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +135,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,23 +154,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FlowsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - FlowsTransport: The transport used by the client instance. + FlowsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -182,14 +182,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: def flow_validation_result_path( project: str, location: str, agent: str, flow: str, ) -> str: - """Return a fully-qualified flow_validation_result string.""" + """Returns a fully-qualified flow_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_validation_result_path(path: str) -> Dict[str, str]: - """Parse a flow_validation_result path into its component segments.""" + """Parses a flow_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path, @@ -198,14 +198,14 @@ def parse_flow_validation_result_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -216,30 +216,52 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, ) return m.groupdict() if m else {} + @staticmethod + def transition_route_group_path( + project: str, location: str, agent: str, flow: str, transition_route_group: str, + ) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( + project=project, + location=location, + agent=agent, + flow=flow, + transition_route_group=transition_route_group, + ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str, str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -248,7 +270,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -261,7 +283,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -272,7 +294,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -283,7 +305,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -294,7 +316,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -308,12 +330,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, FlowsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the flows client. + """Instantiates the flows client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -368,9 +390,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -382,12 +405,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -402,8 +427,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -446,7 +471,6 @@ def create_flow( This corresponds to the ``flow`` 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. @@ -496,10 +520,8 @@ def create_flow( # there are no flattened fields. if not isinstance(request, gcdc_flow.CreateFlowRequest): request = gcdc_flow.CreateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if flow is not None: @@ -543,7 +565,6 @@ def delete_flow( 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. @@ -566,10 +587,8 @@ def delete_flow( # there are no flattened fields. if not isinstance(request, flow.DeleteFlowRequest): request = flow.DeleteFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -610,7 +629,6 @@ def list_flows( 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. @@ -642,10 +660,8 @@ def list_flows( # there are no flattened fields. if not isinstance(request, flow.ListFlowsRequest): request = flow.ListFlowsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -693,7 +709,6 @@ def get_flow( 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. @@ -743,10 +758,8 @@ def get_flow( # there are no flattened fields. if not isinstance(request, flow.GetFlowRequest): request = flow.GetFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -771,7 +784,7 @@ def update_flow( request: gcdc_flow.UpdateFlowRequest = None, *, flow: gcdc_flow.Flow = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -795,7 +808,6 @@ def update_flow( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -845,10 +857,8 @@ def update_flow( # there are no flattened fields. if not isinstance(request, gcdc_flow.UpdateFlowRequest): request = gcdc_flow.UpdateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if flow is not None: request.flow = flow if update_mask is not None: @@ -895,7 +905,6 @@ def train_flow( 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. @@ -937,10 +946,8 @@ def train_flow( # there are no flattened fields. if not isinstance(request, flow.TrainFlowRequest): request = flow.TrainFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -961,8 +968,8 @@ def train_flow( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -985,7 +992,6 @@ def validate_flow( request (google.cloud.dialogflowcx_v3.types.ValidateFlowRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -999,7 +1005,6 @@ def validate_flow( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a flow.ValidateFlowRequest. # There's no risk of modifying the input as we've already verified @@ -1046,7 +1051,6 @@ def get_flow_validation_result( 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. @@ -1075,10 +1079,8 @@ def get_flow_validation_result( # there are no flattened fields. if not isinstance(request, flow.GetFlowValidationResultRequest): request = flow.GetFlowValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1100,6 +1102,133 @@ def get_flow_validation_result( # Done; return the response. return response + def import_flow( + self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (google.cloud.dialogflowcx_v3.types.ImportFlowRequest): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ImportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ImportFlowRequest): + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_flow] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_flow( + self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (google.cloud.dialogflowcx_v3.types.ExportFlowRequest): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ExportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ExportFlowRequest): + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_flow] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3/services/flows/pagers.py b/google/cloud/dialogflowcx_v3/services/flows/pagers.py index 9f4a9009..c4e7b6fb 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/flows/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py index 3789db2a..f2970e47 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/flows/transports/base.py b/google/cloud/dialogflowcx_v3/services/flows/transports/base.py index 9672aeb9..3999d848 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import flow from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class FlowsTransport(abc.ABC): """Abstract transport class for Flows.""" @@ -50,21 +60,24 @@ class FlowsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -139,6 +199,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.import_flow: gapic_v1.method.wrap_method( + self.import_flow, default_timeout=None, client_info=client_info, + ), + self.export_flow: gapic_v1.method.wrap_method( + self.export_flow, default_timeout=None, client_info=client_info, + ), } @property @@ -149,75 +215,84 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_flow( self, - ) -> typing.Callable[ - [gcdc_flow.CreateFlowRequest], - typing.Union[gcdc_flow.Flow, typing.Awaitable[gcdc_flow.Flow]], + ) -> Callable[ + [gcdc_flow.CreateFlowRequest], Union[gcdc_flow.Flow, Awaitable[gcdc_flow.Flow]] ]: raise NotImplementedError() @property def delete_flow( self, - ) -> typing.Callable[ - [flow.DeleteFlowRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [flow.DeleteFlowRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def list_flows( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.ListFlowsRequest], - typing.Union[flow.ListFlowsResponse, typing.Awaitable[flow.ListFlowsResponse]], + Union[flow.ListFlowsResponse, Awaitable[flow.ListFlowsResponse]], ]: raise NotImplementedError() @property def get_flow( self, - ) -> typing.Callable[ - [flow.GetFlowRequest], typing.Union[flow.Flow, typing.Awaitable[flow.Flow]] - ]: + ) -> Callable[[flow.GetFlowRequest], Union[flow.Flow, Awaitable[flow.Flow]]]: raise NotImplementedError() @property def update_flow( self, - ) -> typing.Callable[ - [gcdc_flow.UpdateFlowRequest], - typing.Union[gcdc_flow.Flow, typing.Awaitable[gcdc_flow.Flow]], + ) -> Callable[ + [gcdc_flow.UpdateFlowRequest], Union[gcdc_flow.Flow, Awaitable[gcdc_flow.Flow]] ]: raise NotImplementedError() @property def train_flow( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.TrainFlowRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def validate_flow( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.ValidateFlowRequest], - typing.Union[ - flow.FlowValidationResult, typing.Awaitable[flow.FlowValidationResult] - ], + Union[flow.FlowValidationResult, Awaitable[flow.FlowValidationResult]], ]: raise NotImplementedError() @property def get_flow_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.GetFlowValidationResultRequest], - typing.Union[ - flow.FlowValidationResult, typing.Awaitable[flow.FlowValidationResult] - ], + Union[flow.FlowValidationResult, Awaitable[flow.FlowValidationResult]], + ]: + raise NotImplementedError() + + @property + def import_flow( + self, + ) -> Callable[ + [flow.ImportFlowRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def export_flow( + self, + ) -> Callable[ + [flow.ExportFlowRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: 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 1c543280..92016ca2 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 flow from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import FlowsTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -110,7 +108,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -118,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,24 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -292,7 +265,7 @@ def create_flow(self) -> Callable[[gcdc_flow.CreateFlowRequest], gcdc_flow.Flow] return self._stubs["create_flow"] @property - def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty.Empty]: + def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty_pb2.Empty]: r"""Return a callable for the delete flow method over gRPC. Deletes a specified flow. @@ -311,7 +284,7 @@ def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty.Empty]: self._stubs["delete_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow", request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_flow"] @@ -388,7 +361,7 @@ def update_flow(self) -> Callable[[gcdc_flow.UpdateFlowRequest], gcdc_flow.Flow] return self._stubs["update_flow"] @property - def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations.Operation]: + def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations_pb2.Operation]: r"""Return a callable for the train flow method over gRPC. Trains the specified flow. Note that only the flow in @@ -408,7 +381,7 @@ def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations.Operation]: self._stubs["train_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Flows/TrainFlow", request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_flow"] @@ -468,5 +441,60 @@ def get_flow_validation_result( ) return self._stubs["get_flow_validation_result"] + @property + def import_flow( + self, + ) -> Callable[[flow.ImportFlowRequest], operations_pb2.Operation]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_flow" not in self._stubs: + self._stubs["import_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Flows/ImportFlow", + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_flow"] + + @property + def export_flow( + self, + ) -> Callable[[flow.ExportFlowRequest], operations_pb2.Operation]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_flow" not in self._stubs: + self._stubs["export_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Flows/ExportFlow", + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_flow"] + __all__ = ("FlowsGrpcTransport",) 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 fadbc2f1..2a73cf2f 100644 --- a/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/flows/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import flow from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import FlowsTransport, DEFAULT_CLIENT_INFO from .grpc import FlowsGrpcTransport @@ -57,7 +54,7 @@ class FlowsGrpcAsyncIOTransport(FlowsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -65,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -143,10 +143,10 @@ def __init__( 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 + 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: @@ -155,7 +155,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -163,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,18 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -300,7 +272,9 @@ def create_flow( return self._stubs["create_flow"] @property - def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty.Empty]]: + def delete_flow( + self, + ) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete flow method over gRPC. Deletes a specified flow. @@ -319,7 +293,7 @@ def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty.Empt self._stubs["delete_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Flows/DeleteFlow", request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_flow"] @@ -402,7 +376,7 @@ def update_flow( @property def train_flow( self, - ) -> Callable[[flow.TrainFlowRequest], Awaitable[operations.Operation]]: + ) -> Callable[[flow.TrainFlowRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train flow method over gRPC. Trains the specified flow. Note that only the flow in @@ -422,7 +396,7 @@ def train_flow( self._stubs["train_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Flows/TrainFlow", request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_flow"] @@ -484,5 +458,60 @@ def get_flow_validation_result( ) return self._stubs["get_flow_validation_result"] + @property + def import_flow( + self, + ) -> Callable[[flow.ImportFlowRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_flow" not in self._stubs: + self._stubs["import_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Flows/ImportFlow", + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_flow"] + + @property + def export_flow( + self, + ) -> Callable[[flow.ExportFlowRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_flow" not in self._stubs: + self._stubs["export_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.Flows/ExportFlow", + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_flow"] + __all__ = ("FlowsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/intents/__init__.py b/google/cloud/dialogflowcx_v3/services/intents/__init__.py index 8719a9b6..5a2c263c 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/intents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import IntentsClient from .async_client import IntentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/intents/async_client.py b/google/cloud/dialogflowcx_v3/services/intents/async_client.py index 2a2d271d..bdf87330 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/intents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.intents import pagers from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -52,31 +49,27 @@ class IntentsAsyncClient: parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) intent_path = staticmethod(IntentsClient.intent_path) parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod( IntentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( IntentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(IntentsClient.common_folder_path) parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) parse_common_organization_path = staticmethod( IntentsClient.parse_common_organization_path ) - common_project_path = staticmethod(IntentsClient.common_project_path) parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) parse_common_location_path = staticmethod(IntentsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +84,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: IntentsTransport: The transport used by the client instance. @@ -122,12 +115,12 @@ def transport(self) -> IntentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, IntentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -190,7 +182,6 @@ async def list_intents( 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. @@ -220,7 +211,6 @@ async def list_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -272,7 +262,6 @@ async def get_intent( 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. @@ -304,7 +293,6 @@ async def get_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -356,7 +344,6 @@ async def create_intent( This corresponds to the ``intent`` 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. @@ -388,7 +375,6 @@ async def create_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -419,7 +405,7 @@ async def update_intent( request: gcdc_intent.UpdateIntentRequest = None, *, intent: gcdc_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -443,7 +429,6 @@ async def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -475,7 +460,6 @@ async def update_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -525,7 +509,6 @@ async def delete_intent( 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. @@ -546,7 +529,6 @@ async def delete_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/intents/client.py b/google/cloud/dialogflowcx_v3/services/intents/client.py index 9a4e0a2b..c4a2fd9d 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/client.py +++ b/google/cloud/dialogflowcx_v3/services/intents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,8 +33,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class IntentsClientMeta(type): _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IntentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class IntentsClient(metaclass=IntentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,10 +149,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - IntentsTransport: The transport used by the client instance. + IntentsTransport: The transport used by the client + instance. """ return self._transport @@ -161,14 +161,14 @@ def transport(self) -> IntentsTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -177,14 +177,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -193,7 +193,7 @@ def parse_intent_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -206,7 +206,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -239,7 +239,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -253,12 +253,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IntentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -313,9 +313,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -327,12 +328,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -347,8 +350,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -386,7 +389,6 @@ def list_intents( 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. @@ -418,10 +420,8 @@ def list_intents( # there are no flattened fields. if not isinstance(request, intent.ListIntentsRequest): request = intent.ListIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -469,7 +469,6 @@ def get_intent( 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. @@ -503,10 +502,8 @@ def get_intent( # there are no flattened fields. if not isinstance(request, intent.GetIntentRequest): request = intent.GetIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -554,7 +551,6 @@ def create_intent( This corresponds to the ``intent`` 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. @@ -588,10 +584,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcdc_intent.CreateIntentRequest): request = gcdc_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -618,7 +612,7 @@ def update_intent( request: gcdc_intent.UpdateIntentRequest = None, *, intent: gcdc_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -642,7 +636,6 @@ def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -676,10 +669,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcdc_intent.UpdateIntentRequest): request = gcdc_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -725,7 +716,6 @@ def delete_intent( 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. @@ -748,10 +738,8 @@ def delete_intent( # there are no flattened fields. if not isinstance(request, intent.DeleteIntentRequest): request = intent.DeleteIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/intents/pagers.py b/google/cloud/dialogflowcx_v3/services/intents/pagers.py index c7bd6591..5e40535d 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/intents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py index 41fde33b..974a5810 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/intents/transports/base.py b/google/cloud/dialogflowcx_v3/services/intents/transports/base.py index 64e82a1e..7b147df4 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -48,21 +58,24 @@ class IntentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,47 +191,43 @@ def _prep_wrapped_messages(self, client_info): @property def list_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.ListIntentsRequest], - typing.Union[ - intent.ListIntentsResponse, typing.Awaitable[intent.ListIntentsResponse] - ], + Union[intent.ListIntentsResponse, Awaitable[intent.ListIntentsResponse]], ]: raise NotImplementedError() @property def get_intent( self, - ) -> typing.Callable[ - [intent.GetIntentRequest], - typing.Union[intent.Intent, typing.Awaitable[intent.Intent]], + ) -> Callable[ + [intent.GetIntentRequest], Union[intent.Intent, Awaitable[intent.Intent]] ]: raise NotImplementedError() @property def create_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_intent.CreateIntentRequest], - typing.Union[gcdc_intent.Intent, typing.Awaitable[gcdc_intent.Intent]], + Union[gcdc_intent.Intent, Awaitable[gcdc_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_intent.UpdateIntentRequest], - typing.Union[gcdc_intent.Intent, typing.Awaitable[gcdc_intent.Intent]], + Union[gcdc_intent.Intent, Awaitable[gcdc_intent.Intent]], ]: raise NotImplementedError() @property def delete_intent( self, - ) -> typing.Callable[ - [intent.DeleteIntentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [intent.DeleteIntentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py index db8768da..cf6512f0 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +328,7 @@ def update_intent( return self._stubs["update_intent"] @property - def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: + def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty_pb2.Empty]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent. @@ -374,7 +347,7 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] 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 f66c9c4e..b98be5ac 100644 --- a/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/intents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import intent from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -56,7 +53,7 @@ class IntentsGrpcAsyncIOTransport(IntentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -363,7 +335,7 @@ def update_intent( @property def delete_intent( self, - ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent. @@ -382,7 +354,7 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] diff --git a/google/cloud/dialogflowcx_v3/services/pages/__init__.py b/google/cloud/dialogflowcx_v3/services/pages/__init__.py index 4fff3f52..c5a52656 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/pages/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PagesClient from .async_client import PagesAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/pages/async_client.py b/google/cloud/dialogflowcx_v3/services/pages/async_client.py index eb761cff..79d410c1 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/pages/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.pages import pagers 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport from .client import PagesClient @@ -61,29 +58,25 @@ class PagesAsyncClient: ) webhook_path = staticmethod(PagesClient.webhook_path) parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) - common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( PagesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(PagesClient.common_folder_path) parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) - common_organization_path = staticmethod(PagesClient.common_organization_path) parse_common_organization_path = staticmethod( PagesClient.parse_common_organization_path ) - common_project_path = staticmethod(PagesClient.common_project_path) parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) - common_location_path = staticmethod(PagesClient.common_location_path) parse_common_location_path = staticmethod(PagesClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -98,7 +91,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -115,7 +108,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PagesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: PagesTransport: The transport used by the client instance. @@ -129,12 +122,12 @@ def transport(self) -> PagesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, PagesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the pages client. + """Instantiates the pages client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -166,7 +159,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PagesClient( credentials=credentials, transport=transport, @@ -196,7 +188,6 @@ async def list_pages( 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. @@ -226,7 +217,6 @@ async def list_pages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -278,7 +268,6 @@ async def get_page( 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. @@ -325,7 +314,6 @@ async def get_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -377,7 +365,6 @@ async def create_page( This corresponds to the ``page`` 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. @@ -424,7 +411,6 @@ async def create_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if page is not None: @@ -455,7 +441,7 @@ async def update_page( request: gcdc_page.UpdatePageRequest = None, *, page: gcdc_page.Page = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -479,7 +465,6 @@ async def update_page( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -526,7 +511,6 @@ async def update_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if page is not None: request.page = page if update_mask is not None: @@ -576,7 +560,6 @@ async def delete_page( 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. @@ -597,7 +580,6 @@ async def delete_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/pages/client.py b/google/cloud/dialogflowcx_v3/services/pages/client.py index 25c1d30c..a74f7673 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/client.py +++ b/google/cloud/dialogflowcx_v3/services/pages/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -36,8 +34,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PagesGrpcTransport from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class PagesClientMeta(type): _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[PagesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -79,7 +76,8 @@ class PagesClient(metaclass=PagesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -113,7 +111,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -130,7 +129,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -149,10 +148,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PagesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PagesTransport: The transport used by the client instance. + PagesTransport: The transport used by the client + instance. """ return self._transport @@ -160,14 +160,14 @@ def transport(self) -> PagesTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -176,14 +176,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -192,14 +192,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -210,14 +210,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -228,7 +228,7 @@ def parse_page_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -239,7 +239,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -248,14 +248,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -264,7 +264,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -277,7 +277,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -288,7 +288,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -299,7 +299,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -310,7 +310,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -324,12 +324,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PagesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the pages client. + """Instantiates the pages client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -384,9 +384,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -398,12 +399,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -418,8 +421,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -456,7 +459,6 @@ def list_pages( 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. @@ -488,10 +490,8 @@ def list_pages( # there are no flattened fields. if not isinstance(request, page.ListPagesRequest): request = page.ListPagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -539,7 +539,6 @@ def get_page( 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. @@ -588,10 +587,8 @@ def get_page( # there are no flattened fields. if not isinstance(request, page.GetPageRequest): request = page.GetPageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -639,7 +636,6 @@ def create_page( This corresponds to the ``page`` 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. @@ -688,10 +684,8 @@ def create_page( # there are no flattened fields. if not isinstance(request, gcdc_page.CreatePageRequest): request = gcdc_page.CreatePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if page is not None: @@ -718,7 +712,7 @@ def update_page( request: gcdc_page.UpdatePageRequest = None, *, page: gcdc_page.Page = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -742,7 +736,6 @@ def update_page( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -791,10 +784,8 @@ def update_page( # there are no flattened fields. if not isinstance(request, gcdc_page.UpdatePageRequest): request = gcdc_page.UpdatePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if page is not None: request.page = page if update_mask is not None: @@ -840,7 +831,6 @@ def delete_page( 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. @@ -863,10 +853,8 @@ def delete_page( # there are no flattened fields. if not isinstance(request, page.DeletePageRequest): request = page.DeletePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/pages/pagers.py b/google/cloud/dialogflowcx_v3/services/pages/pagers.py index 6334e82a..0a2d933f 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/pages/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py index de980d7b..fff7089d 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/pages/transports/base.py b/google/cloud/dialogflowcx_v3/services/pages/transports/base.py index ce7f72f8..3325368a 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class PagesTransport(abc.ABC): """Abstract transport class for Pages.""" @@ -48,21 +58,24 @@ class PagesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,44 +191,39 @@ def _prep_wrapped_messages(self, client_info): @property def list_pages( self, - ) -> typing.Callable[ + ) -> Callable[ [page.ListPagesRequest], - typing.Union[page.ListPagesResponse, typing.Awaitable[page.ListPagesResponse]], + Union[page.ListPagesResponse, Awaitable[page.ListPagesResponse]], ]: raise NotImplementedError() @property def get_page( self, - ) -> typing.Callable[ - [page.GetPageRequest], typing.Union[page.Page, typing.Awaitable[page.Page]] - ]: + ) -> Callable[[page.GetPageRequest], Union[page.Page, Awaitable[page.Page]]]: raise NotImplementedError() @property def create_page( self, - ) -> typing.Callable[ - [gcdc_page.CreatePageRequest], - typing.Union[gcdc_page.Page, typing.Awaitable[gcdc_page.Page]], + ) -> Callable[ + [gcdc_page.CreatePageRequest], Union[gcdc_page.Page, Awaitable[gcdc_page.Page]] ]: raise NotImplementedError() @property def update_page( self, - ) -> typing.Callable[ - [gcdc_page.UpdatePageRequest], - typing.Union[gcdc_page.Page, typing.Awaitable[gcdc_page.Page]], + ) -> Callable[ + [gcdc_page.UpdatePageRequest], Union[gcdc_page.Page, Awaitable[gcdc_page.Page]] ]: raise NotImplementedError() @property def delete_page( self, - ) -> typing.Callable[ - [page.DeletePageRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [page.DeletePageRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py index 07854d83..8d8361f7 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 page from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PagesTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -108,7 +106,9 @@ def __init__( 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) @@ -116,70 +116,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -187,23 +167,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,7 +182,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -234,13 +205,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -347,7 +320,7 @@ def update_page(self) -> Callable[[gcdc_page.UpdatePageRequest], gcdc_page.Page] return self._stubs["update_page"] @property - def delete_page(self) -> Callable[[page.DeletePageRequest], empty.Empty]: + def delete_page(self) -> Callable[[page.DeletePageRequest], empty_pb2.Empty]: r"""Return a callable for the delete page method over gRPC. Deletes the specified page. @@ -366,7 +339,7 @@ def delete_page(self) -> Callable[[page.DeletePageRequest], empty.Empty]: self._stubs["delete_page"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Pages/DeletePage", request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_page"] 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 077eaa33..3f084d95 100644 --- a/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/pages/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PagesTransport, DEFAULT_CLIENT_INFO from .grpc import PagesGrpcTransport @@ -55,7 +52,7 @@ class PagesGrpcAsyncIOTransport(PagesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -63,7 +60,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -141,10 +141,10 @@ def __init__( 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 + 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: @@ -153,7 +153,9 @@ def __init__( 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) @@ -161,70 +163,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -232,17 +213,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -357,7 +329,9 @@ def update_page( return self._stubs["update_page"] @property - def delete_page(self) -> Callable[[page.DeletePageRequest], Awaitable[empty.Empty]]: + def delete_page( + self, + ) -> Callable[[page.DeletePageRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete page method over gRPC. Deletes the specified page. @@ -376,7 +350,7 @@ def delete_page(self) -> Callable[[page.DeletePageRequest], Awaitable[empty.Empt self._stubs["delete_page"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Pages/DeletePage", request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_page"] diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py index 66f0a799..d8b471f4 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SecuritySettingsServiceClient from .async_client import SecuritySettingsServiceAsyncClient 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 4d2b0dc0..0ddde9bc 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.security_settings_service import pagers @@ -33,8 +31,7 @@ from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport from .client import SecuritySettingsServiceClient @@ -54,33 +51,28 @@ class SecuritySettingsServiceAsyncClient: parse_security_settings_path = staticmethod( SecuritySettingsServiceClient.parse_security_settings_path ) - common_billing_account_path = staticmethod( SecuritySettingsServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SecuritySettingsServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) parse_common_folder_path = staticmethod( SecuritySettingsServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( SecuritySettingsServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( SecuritySettingsServiceClient.parse_common_organization_path ) - common_project_path = staticmethod( SecuritySettingsServiceClient.common_project_path ) parse_common_project_path = staticmethod( SecuritySettingsServiceClient.parse_common_project_path ) - common_location_path = staticmethod( SecuritySettingsServiceClient.common_location_path ) @@ -90,7 +82,8 @@ class SecuritySettingsServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -105,7 +98,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -122,7 +115,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecuritySettingsServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SecuritySettingsServiceTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> SecuritySettingsServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security settings service client. + """Instantiates the security settings service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SecuritySettingsServiceClient( credentials=credentials, transport=transport, @@ -214,7 +206,6 @@ async def create_security_settings( This corresponds to the ``security_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -245,7 +236,6 @@ async def create_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if security_settings is not None: @@ -295,7 +285,6 @@ async def get_security_settings( 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. @@ -326,7 +315,6 @@ async def get_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -355,7 +343,7 @@ async def update_security_settings( request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -382,7 +370,6 @@ async def update_security_settings( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -413,7 +400,6 @@ async def update_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_settings is not None: request.security_settings = security_settings if update_mask is not None: @@ -465,7 +451,6 @@ async def list_security_settings( 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. @@ -495,7 +480,6 @@ async def list_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -550,7 +534,6 @@ async def delete_security_settings( 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. @@ -571,7 +554,6 @@ async def delete_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 792e4ac1..dd9c2e97 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,8 +35,7 @@ from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SecuritySettingsServiceGrpcTransport from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class SecuritySettingsServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SecuritySettingsServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta) @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,10 +153,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecuritySettingsServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecuritySettingsServiceTransport: The transport used by the client instance. + SecuritySettingsServiceTransport: The transport used by the client + instance. """ return self._transport @@ -165,14 +165,14 @@ def transport(self) -> SecuritySettingsServiceTransport: def security_settings_path( project: str, location: str, security_settings: str, ) -> str: - """Return a fully-qualified security_settings string.""" + """Returns a fully-qualified security_settings string.""" return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @staticmethod def parse_security_settings_path(path: str) -> Dict[str, str]: - """Parse a security_settings path into its component segments.""" + """Parses a security_settings path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path, @@ -181,7 +181,7 @@ def parse_security_settings_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -194,7 +194,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -205,7 +205,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -216,7 +216,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -227,7 +227,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -241,12 +241,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SecuritySettingsServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security settings service client. + """Instantiates the security settings service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -301,9 +301,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -315,12 +316,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -335,8 +338,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -383,7 +386,6 @@ def create_security_settings( This corresponds to the ``security_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -418,10 +420,8 @@ def create_security_settings( request, gcdc_security_settings.CreateSecuritySettingsRequest ): request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if security_settings is not None: @@ -467,7 +467,6 @@ def get_security_settings( 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. @@ -500,10 +499,8 @@ def get_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.GetSecuritySettingsRequest): request = security_settings.GetSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -528,7 +525,7 @@ def update_security_settings( request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -555,7 +552,6 @@ def update_security_settings( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -590,10 +586,8 @@ def update_security_settings( request, gcdc_security_settings.UpdateSecuritySettingsRequest ): request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_settings is not None: request.security_settings = security_settings if update_mask is not None: @@ -641,7 +635,6 @@ def list_security_settings( 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. @@ -673,10 +666,8 @@ def list_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.ListSecuritySettingsRequest): request = security_settings.ListSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -727,7 +718,6 @@ def delete_security_settings( 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. @@ -750,10 +740,8 @@ def delete_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): request = security_settings.DeleteSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py index 92dadcce..41ba5aca 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py index fc2aea1c..8f3a8c8b 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 d1bc583f..6ed6a73b 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import security_settings from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SecuritySettingsServiceTransport(abc.ABC): """Abstract transport class for SecuritySettingsService.""" @@ -50,21 +60,24 @@ class SecuritySettingsServiceTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def create_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_security_settings.CreateSecuritySettingsRequest], - typing.Union[ + Union[ gcdc_security_settings.SecuritySettings, - typing.Awaitable[gcdc_security_settings.SecuritySettings], + Awaitable[gcdc_security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def create_security_settings( @property def get_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.GetSecuritySettingsRequest], - typing.Union[ + Union[ security_settings.SecuritySettings, - typing.Awaitable[security_settings.SecuritySettings], + Awaitable[security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_security_settings( @property def update_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_security_settings.UpdateSecuritySettingsRequest], - typing.Union[ + Union[ gcdc_security_settings.SecuritySettings, - typing.Awaitable[gcdc_security_settings.SecuritySettings], + Awaitable[gcdc_security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def update_security_settings( @property def list_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.ListSecuritySettingsRequest], - typing.Union[ + Union[ security_settings.ListSecuritySettingsResponse, - typing.Awaitable[security_settings.ListSecuritySettingsResponse], + Awaitable[security_settings.ListSecuritySettingsResponse], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def list_security_settings( @property def delete_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.DeleteSecuritySettingsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py index 411496f9..cf0d1917 100644 --- a/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/security_settings_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -110,7 +108,9 @@ def __init__( 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) @@ -118,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,23 +169,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -213,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -236,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -375,7 +348,7 @@ def list_security_settings( @property def delete_security_settings( self, - ) -> Callable[[security_settings.DeleteSecuritySettingsRequest], empty.Empty]: + ) -> Callable[[security_settings.DeleteSecuritySettingsRequest], empty_pb2.Empty]: r"""Return a callable for the delete security settings method over gRPC. Deletes the specified @@ -395,7 +368,7 @@ def delete_security_settings( self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings", request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_security_settings"] 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 0464daac..5fa7c384 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .grpc import SecuritySettingsServiceGrpcTransport @@ -57,7 +54,7 @@ class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTranspo def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -65,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -143,10 +143,10 @@ def __init__( 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 + 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: @@ -155,7 +155,9 @@ def __init__( 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) @@ -163,70 +165,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,17 +215,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -380,7 +352,7 @@ def list_security_settings( def delete_security_settings( self, ) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], Awaitable[empty.Empty] + [security_settings.DeleteSecuritySettingsRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete security settings method over gRPC. @@ -401,7 +373,7 @@ def delete_security_settings( self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.SecuritySettingsService/DeleteSecuritySettings", request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_security_settings"] diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py index c0dca267..cbd406b4 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionEntityTypesClient from .async_client import SessionEntityTypesAsyncClient 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 5a5ac1f7..74b9046a 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflowcx_v3.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport from .client import SessionEntityTypesClient @@ -57,31 +54,26 @@ class SessionEntityTypesAsyncClient: parse_session_entity_type_path = staticmethod( SessionEntityTypesClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionEntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionEntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod( SessionEntityTypesClient.parse_common_folder_path ) - common_organization_path = staticmethod( SessionEntityTypesClient.common_organization_path ) parse_common_organization_path = staticmethod( SessionEntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) parse_common_project_path = staticmethod( SessionEntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) parse_common_location_path = staticmethod( SessionEntityTypesClient.parse_common_location_path @@ -89,7 +81,8 @@ class SessionEntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionEntityTypesTransport: The transport used by the client instance. @@ -136,12 +129,12 @@ def transport(self) -> SessionEntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -173,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -209,7 +201,6 @@ async def list_session_entity_types( 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. @@ -239,7 +230,6 @@ async def list_session_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -295,7 +285,6 @@ async def get_session_entity_type( 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. @@ -336,7 +325,6 @@ async def get_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -371,8 +359,6 @@ async def create_session_entity_type( metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Args: request (:class:`google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest`): @@ -397,7 +383,6 @@ async def create_session_entity_type( This corresponds to the ``session_entity_type`` 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. @@ -438,7 +423,6 @@ async def create_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -469,7 +453,7 @@ async def update_session_entity_type( request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -498,7 +482,6 @@ async def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -539,7 +522,6 @@ async def update_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -594,7 +576,6 @@ async def delete_session_entity_type( 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. @@ -615,7 +596,6 @@ async def delete_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 ee3ac536..d0a7167d 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,8 +36,7 @@ from google.cloud.dialogflowcx_v3.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionEntityTypesGrpcTransport from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class SessionEntityTypesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SessionEntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,10 +156,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionEntityTypesTransport: The transport used by the client instance. + SessionEntityTypesTransport: The transport used by the client + instance. """ return self._transport @@ -168,7 +168,7 @@ def transport(self) -> SessionEntityTypesTransport: def session_entity_type_path( project: str, location: str, agent: str, session: str, entity_type: str, ) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -179,7 +179,7 @@ def session_entity_type_path( @staticmethod def parse_session_entity_type_path(path: str) -> Dict[str, str]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -188,7 +188,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -201,7 +201,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -248,12 +248,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionEntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -308,9 +308,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -322,12 +323,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -342,8 +345,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -386,7 +389,6 @@ def list_session_entity_types( 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. @@ -418,10 +420,8 @@ def list_session_entity_types( # there are no flattened fields. if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): request = session_entity_type.ListSessionEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -475,7 +475,6 @@ def get_session_entity_type( 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. @@ -518,10 +517,8 @@ def get_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): request = session_entity_type.GetSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -552,8 +549,6 @@ def create_session_entity_type( metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Args: request (google.cloud.dialogflowcx_v3.types.CreateSessionEntityTypeRequest): @@ -578,7 +573,6 @@ def create_session_entity_type( This corresponds to the ``session_entity_type`` 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. @@ -623,10 +617,8 @@ def create_session_entity_type( request, gcdc_session_entity_type.CreateSessionEntityTypeRequest ): request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -655,7 +647,7 @@ def update_session_entity_type( request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -684,7 +676,6 @@ def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -729,10 +720,8 @@ def update_session_entity_type( request, gcdc_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -785,7 +774,6 @@ def delete_session_entity_type( 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. @@ -808,10 +796,8 @@ def delete_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): request = session_entity_type.DeleteSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py index 3c6d5582..13c64382 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py index 606f9116..633fd32c 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 54ae7a03..76f2dd22 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import session_entity_type from google.cloud.dialogflowcx_v3.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -50,21 +60,24 @@ class SessionEntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_session_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.ListSessionEntityTypesRequest], - typing.Union[ + Union[ session_entity_type.ListSessionEntityTypesResponse, - typing.Awaitable[session_entity_type.ListSessionEntityTypesResponse], + Awaitable[session_entity_type.ListSessionEntityTypesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_session_entity_types( @property def get_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.GetSessionEntityTypeRequest], - typing.Union[ + Union[ session_entity_type.SessionEntityType, - typing.Awaitable[session_entity_type.SessionEntityType], + Awaitable[session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_session_entity_type( @property def create_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcdc_session_entity_type.SessionEntityType, - typing.Awaitable[gcdc_session_entity_type.SessionEntityType], + Awaitable[gcdc_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_session_entity_type( @property def update_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcdc_session_entity_type.SessionEntityType, - typing.Awaitable[gcdc_session_entity_type.SessionEntityType], + Awaitable[gcdc_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.DeleteSessionEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py index ff48f310..b1d2fcef 100644 --- a/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/session_entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,9 @@ def __init__( 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) @@ -119,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,23 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -322,8 +295,6 @@ def create_session_entity_type( r"""Return a callable for the create session entity type method over gRPC. Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Returns: Callable[[~.CreateSessionEntityTypeRequest], @@ -375,7 +346,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> Callable[[session_entity_type.DeleteSessionEntityTypeRequest], empty.Empty]: + ) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete session entity type method over gRPC. Deletes the specified session entity type. @@ -394,7 +367,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] 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 ded1d164..e9cc5a9d 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import SessionEntityTypesGrpcTransport @@ -58,7 +55,7 @@ class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -326,8 +298,6 @@ def create_session_entity_type( r"""Return a callable for the create session entity type method over gRPC. Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Returns: Callable[[~.CreateSessionEntityTypeRequest], @@ -380,7 +350,7 @@ def update_session_entity_type( def delete_session_entity_type( self, ) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty.Empty] + [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete session entity type method over gRPC. @@ -400,7 +370,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflowcx_v3/services/sessions/__init__.py b/google/cloud/dialogflowcx_v3/services/sessions/__init__.py index 3b2a59a9..0adeafb9 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionsClient from .async_client import SessionsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py index b11caaa2..7257e797 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,16 +29,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 audio_config from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import session - from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -80,31 +77,27 @@ class SessionsAsyncClient: ) webhook_path = staticmethod(SessionsClient.webhook_path) parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) - common_billing_account_path = staticmethod( SessionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionsClient.common_folder_path) parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) parse_common_organization_path = staticmethod( SessionsClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionsClient.common_project_path) parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) parse_common_location_path = staticmethod(SessionsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -119,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -136,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionsTransport: The transport used by the client instance. @@ -150,12 +143,12 @@ def transport(self) -> SessionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -187,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -215,7 +207,6 @@ async def detect_intent( Args: request (:class:`google.cloud.dialogflowcx_v3.types.DetectIntentRequest`): 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. timeout (float): The timeout for this request. @@ -229,7 +220,6 @@ async def detect_intent( """ # Create or coerce a protobuf request object. - request = session.DetectIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -240,7 +230,10 @@ async def detect_intent( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, @@ -329,7 +322,14 @@ def streaming_detect_intent( Each recognition_result represents a more complete transcript of what the user said. The last recognition_result has is_final set to true. - 2. The last message contains detect_intent_response. + 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. """ @@ -361,7 +361,6 @@ async def match_intent( Args: request (:class:`google.cloud.dialogflowcx_v3.types.MatchIntentRequest`): The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -373,7 +372,6 @@ async def match_intent( Response of [MatchIntent][]. """ # Create or coerce a protobuf request object. - request = session.MatchIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -415,7 +413,6 @@ async def fulfill_intent( Args: request (:class:`google.cloud.dialogflowcx_v3.types.FulfillIntentRequest`): The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,7 +424,6 @@ async def fulfill_intent( Response of [FulfillIntent][] """ # Create or coerce a protobuf request object. - request = session.FulfillIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflowcx_v3/services/sessions/client.py b/google/cloud/dialogflowcx_v3/services/sessions/client.py index 9090501e..a90fc04d 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/client.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -45,7 +43,6 @@ 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 - from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -64,7 +61,7 @@ class SessionsClientMeta(type): _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SessionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -91,7 +88,8 @@ class SessionsClient(metaclass=SessionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -125,7 +123,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -142,7 +141,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -161,10 +160,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionsTransport: The transport used by the client instance. + SessionsTransport: The transport used by the client + instance. """ return self._transport @@ -172,14 +172,14 @@ def transport(self) -> SessionsTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -188,14 +188,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -204,14 +204,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -222,14 +222,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -238,14 +238,14 @@ def parse_page_path(path: str) -> Dict[str, str]: @staticmethod def session_path(project: str, location: str, agent: str, session: str,) -> str: - """Return a fully-qualified session string.""" + """Returns a fully-qualified session string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format( project=project, location=location, agent=agent, session=session, ) @staticmethod def parse_session_path(path: str) -> Dict[str, str]: - """Parse a session path into its component segments.""" + """Parses a session path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path, @@ -256,7 +256,7 @@ def parse_session_path(path: str) -> Dict[str, str]: def session_entity_type_path( project: str, location: str, agent: str, session: str, entity_type: str, ) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -267,7 +267,7 @@ def session_entity_type_path( @staticmethod def parse_session_entity_type_path(path: str) -> Dict[str, str]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -278,7 +278,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -289,7 +289,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -298,14 +298,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -314,7 +314,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -327,7 +327,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -338,7 +338,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -349,7 +349,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -360,7 +360,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -374,12 +374,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -434,9 +434,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -448,12 +449,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -468,8 +471,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -504,7 +507,6 @@ def detect_intent( Args: request (google.cloud.dialogflowcx_v3.types.DetectIntentRequest): 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. timeout (float): The timeout for this request. @@ -518,7 +520,6 @@ def detect_intent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.DetectIntentRequest. # There's no risk of modifying the input as we've already verified @@ -613,7 +614,14 @@ def streaming_detect_intent( Each recognition_result represents a more complete transcript of what the user said. The last recognition_result has is_final set to true. - 2. The last message contains detect_intent_response. + 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. """ @@ -641,7 +649,6 @@ def match_intent( Args: request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -653,7 +660,6 @@ def match_intent( Response of [MatchIntent][]. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.MatchIntentRequest. # There's no risk of modifying the input as we've already verified @@ -696,7 +702,6 @@ def fulfill_intent( Args: request (google.cloud.dialogflowcx_v3.types.FulfillIntentRequest): The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -708,7 +713,6 @@ def fulfill_intent( Response of [FulfillIntent][] """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.FulfillIntentRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py index 0ca6c76e..db0f7d04 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py index 410fe8c0..e995fc1a 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -37,6 +36,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -46,21 +56,24 @@ class SessionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -69,13 +82,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -83,28 +96,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -115,7 +175,10 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, @@ -136,22 +199,20 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.DetectIntentRequest], - typing.Union[ - session.DetectIntentResponse, typing.Awaitable[session.DetectIntentResponse] - ], + Union[session.DetectIntentResponse, Awaitable[session.DetectIntentResponse]], ]: raise NotImplementedError() @property def streaming_detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.StreamingDetectIntentRequest], - typing.Union[ + Union[ session.StreamingDetectIntentResponse, - typing.Awaitable[session.StreamingDetectIntentResponse], + Awaitable[session.StreamingDetectIntentResponse], ], ]: raise NotImplementedError() @@ -159,23 +220,18 @@ def streaming_detect_intent( @property def match_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.MatchIntentRequest], - typing.Union[ - session.MatchIntentResponse, typing.Awaitable[session.MatchIntentResponse] - ], + Union[session.MatchIntentResponse, Awaitable[session.MatchIntentResponse]], ]: raise NotImplementedError() @property def fulfill_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.FulfillIntentRequest], - typing.Union[ - session.FulfillIntentResponse, - typing.Awaitable[session.FulfillIntentResponse], - ], + Union[session.FulfillIntentResponse, Awaitable[session.FulfillIntentResponse]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py index b3d708f1..3b5a5fbd 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) 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 eb290674..94a6f61c 100644 --- a/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/sessions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -56,7 +53,7 @@ class SessionsGrpcAsyncIOTransport(SessionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py b/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py index 77517b44..359c8900 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TestCasesClient from .async_client import TestCasesAsyncClient 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 4f8262ae..aadcc2f5 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,9 +31,8 @@ from google.cloud.dialogflowcx_v3.services.test_cases import pagers from google.cloud.dialogflowcx_v3.types import test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport from .client import TestCasesClient @@ -78,25 +75,20 @@ class TestCasesAsyncClient: ) webhook_path = staticmethod(TestCasesClient.webhook_path) parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) - common_billing_account_path = staticmethod( TestCasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TestCasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TestCasesClient.common_folder_path) parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) - common_organization_path = staticmethod(TestCasesClient.common_organization_path) parse_common_organization_path = staticmethod( TestCasesClient.parse_common_organization_path ) - common_project_path = staticmethod(TestCasesClient.common_project_path) parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) - common_location_path = staticmethod(TestCasesClient.common_location_path) parse_common_location_path = staticmethod( TestCasesClient.parse_common_location_path @@ -104,7 +96,8 @@ class TestCasesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -119,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -136,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TestCasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TestCasesTransport: The transport used by the client instance. @@ -150,12 +143,12 @@ def transport(self) -> TestCasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TestCasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the test cases client. + """Instantiates the test cases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -187,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TestCasesClient( credentials=credentials, transport=transport, @@ -217,7 +209,6 @@ async def list_test_cases( 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. @@ -247,7 +238,6 @@ async def list_test_cases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -299,7 +289,6 @@ async def batch_delete_test_cases( 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. @@ -320,7 +309,6 @@ async def batch_delete_test_cases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -365,7 +353,6 @@ async def get_test_case( 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. @@ -390,7 +377,6 @@ async def get_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -442,7 +428,6 @@ async def create_test_case( This corresponds to the ``test_case`` 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. @@ -467,7 +452,6 @@ async def create_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if test_case is not None: @@ -498,7 +482,7 @@ async def update_test_case( request: gcdc_test_case.UpdateTestCaseRequest = None, *, test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -525,7 +509,6 @@ async def update_test_case( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -550,7 +533,6 @@ async def update_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if test_case is not None: request.test_case = test_case if update_mask is not None: @@ -592,7 +574,6 @@ async def run_test_case( request (:class:`google.cloud.dialogflowcx_v3.types.RunTestCaseRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -610,7 +591,6 @@ async def run_test_case( """ # Create or coerce a protobuf request object. - request = test_case.RunTestCaseRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -655,7 +635,6 @@ async def batch_run_test_cases( request (:class:`google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -673,7 +652,6 @@ async def batch_run_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.BatchRunTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -718,7 +696,6 @@ async def calculate_coverage( request (:class:`google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -732,7 +709,6 @@ async def calculate_coverage( """ # Create or coerce a protobuf request object. - request = test_case.CalculateCoverageRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -772,7 +748,6 @@ async def import_test_cases( request (:class:`google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -790,7 +765,6 @@ async def import_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.ImportTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -837,7 +811,6 @@ async def export_test_cases( request (:class:`google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -855,7 +828,6 @@ async def export_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.ExportTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -910,7 +882,6 @@ async def list_test_case_results( 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. @@ -940,7 +911,6 @@ async def list_test_case_results( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -970,6 +940,77 @@ async def list_test_case_results( # Done; return the response. return response + async def get_test_case_result( + self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = 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`): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + 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.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # 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 = test_case.GetTestCaseResultRequest(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_test_case_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/client.py b/google/cloud/dialogflowcx_v3/services/test_cases/client.py index 0d882cc7..8abbf979 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/client.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,9 +35,8 @@ from google.cloud.dialogflowcx_v3.services.test_cases import pagers from google.cloud.dialogflowcx_v3.types import test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TestCasesGrpcTransport from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class TestCasesClientMeta(type): _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[TestCasesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class TestCasesClient(metaclass=TestCasesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TestCasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TestCasesTransport: The transport used by the client instance. + TestCasesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path, @@ -181,14 +181,14 @@ def parse_agent_path(path: str) -> Dict[str, str]: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -199,14 +199,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: def environment_path( project: str, location: str, agent: str, environment: str, ) -> str: - """Return a fully-qualified environment string.""" + """Returns a fully-qualified environment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @staticmethod def parse_environment_path(path: str) -> Dict[str, str]: - """Parse a environment path into its component segments.""" + """Parses a environment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path, @@ -215,14 +215,14 @@ def parse_environment_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -231,14 +231,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -249,14 +249,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -265,14 +265,14 @@ def parse_page_path(path: str) -> Dict[str, str]: @staticmethod def test_case_path(project: str, location: str, agent: str, test_case: str,) -> str: - """Return a fully-qualified test_case string.""" + """Returns a fully-qualified test_case string.""" return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( project=project, location=location, agent=agent, test_case=test_case, ) @staticmethod def parse_test_case_path(path: str) -> Dict[str, str]: - """Parse a test_case path into its component segments.""" + """Parses a test_case path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path, @@ -283,7 +283,7 @@ def parse_test_case_path(path: str) -> Dict[str, str]: def test_case_result_path( project: str, location: str, agent: str, test_case: str, result: str, ) -> str: - """Return a fully-qualified test_case_result string.""" + """Returns a fully-qualified test_case_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -294,7 +294,7 @@ def test_case_result_path( @staticmethod def parse_test_case_result_path(path: str) -> Dict[str, str]: - """Parse a test_case_result path into its component segments.""" + """Parses a test_case_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path, @@ -305,7 +305,7 @@ def parse_test_case_result_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -316,7 +316,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -325,14 +325,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -341,7 +341,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -354,7 +354,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -365,7 +365,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -376,7 +376,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -387,7 +387,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -401,12 +401,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TestCasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the test cases client. + """Instantiates the test cases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -461,9 +461,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -475,12 +476,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -495,8 +498,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -533,7 +536,6 @@ def list_test_cases( 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. @@ -565,10 +567,8 @@ def list_test_cases( # there are no flattened fields. if not isinstance(request, test_case.ListTestCasesRequest): request = test_case.ListTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -616,7 +616,6 @@ def batch_delete_test_cases( 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. @@ -639,10 +638,8 @@ def batch_delete_test_cases( # there are no flattened fields. if not isinstance(request, test_case.BatchDeleteTestCasesRequest): request = test_case.BatchDeleteTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -683,7 +680,6 @@ def get_test_case( 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. @@ -710,10 +706,8 @@ def get_test_case( # there are no flattened fields. if not isinstance(request, test_case.GetTestCaseRequest): request = test_case.GetTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -761,7 +755,6 @@ def create_test_case( This corresponds to the ``test_case`` 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. @@ -788,10 +781,8 @@ def create_test_case( # there are no flattened fields. if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): request = gcdc_test_case.CreateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if test_case is not None: @@ -818,7 +809,7 @@ def update_test_case( request: gcdc_test_case.UpdateTestCaseRequest = None, *, test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -845,7 +836,6 @@ def update_test_case( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -872,10 +862,8 @@ def update_test_case( # there are no flattened fields. if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): request = gcdc_test_case.UpdateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if test_case is not None: request.test_case = test_case if update_mask is not None: @@ -913,7 +901,6 @@ def run_test_case( request (google.cloud.dialogflowcx_v3.types.RunTestCaseRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -931,7 +918,6 @@ def run_test_case( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.RunTestCaseRequest. # There's no risk of modifying the input as we've already verified @@ -977,7 +963,6 @@ def batch_run_test_cases( request (google.cloud.dialogflowcx_v3.types.BatchRunTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -995,7 +980,6 @@ def batch_run_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.BatchRunTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1041,7 +1025,6 @@ def calculate_coverage( request (google.cloud.dialogflowcx_v3.types.CalculateCoverageRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1055,7 +1038,6 @@ def calculate_coverage( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.CalculateCoverageRequest. # There's no risk of modifying the input as we've already verified @@ -1096,7 +1078,6 @@ def import_test_cases( request (google.cloud.dialogflowcx_v3.types.ImportTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1114,7 +1095,6 @@ def import_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.ImportTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1162,7 +1142,6 @@ def export_test_cases( request (google.cloud.dialogflowcx_v3.types.ExportTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1180,7 +1159,6 @@ def export_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.ExportTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1236,7 +1214,6 @@ def list_test_case_results( 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. @@ -1268,10 +1245,8 @@ def list_test_case_results( # there are no flattened fields. if not isinstance(request, test_case.ListTestCaseResultsRequest): request = test_case.ListTestCaseResultsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1297,6 +1272,77 @@ def list_test_case_results( # Done; return the response. return response + def get_test_case_result( + self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (google.cloud.dialogflowcx_v3.types.GetTestCaseResultRequest): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + 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.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # 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 test_case.GetTestCaseResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseResultRequest): + request = test_case.GetTestCaseResultRequest(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_test_case_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py b/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py index e037052a..1a16ad0e 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py index 0c356952..caa2815b 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 a4b8f4e6..4cd9a366 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TestCasesTransport(abc.ABC): """Abstract transport class for TestCases.""" @@ -50,21 +60,24 @@ class TestCasesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -152,6 +212,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_test_case_result: gapic_v1.method.wrap_method( + self.get_test_case_result, + default_timeout=None, + client_info=client_info, + ), } @property @@ -162,11 +227,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ListTestCasesRequest], - typing.Union[ - test_case.ListTestCasesResponse, - typing.Awaitable[test_case.ListTestCasesResponse], + Union[ + test_case.ListTestCasesResponse, Awaitable[test_case.ListTestCasesResponse] ], ]: raise NotImplementedError() @@ -174,69 +238,65 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.BatchDeleteTestCasesRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.GetTestCaseRequest], - typing.Union[test_case.TestCase, typing.Awaitable[test_case.TestCase]], + Union[test_case.TestCase, Awaitable[test_case.TestCase]], ]: raise NotImplementedError() @property def create_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_test_case.CreateTestCaseRequest], - typing.Union[ - gcdc_test_case.TestCase, typing.Awaitable[gcdc_test_case.TestCase] - ], + Union[gcdc_test_case.TestCase, Awaitable[gcdc_test_case.TestCase]], ]: raise NotImplementedError() @property def update_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_test_case.UpdateTestCaseRequest], - typing.Union[ - gcdc_test_case.TestCase, typing.Awaitable[gcdc_test_case.TestCase] - ], + Union[gcdc_test_case.TestCase, Awaitable[gcdc_test_case.TestCase]], ]: raise NotImplementedError() @property def run_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.RunTestCaseRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_run_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.BatchRunTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def calculate_coverage( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.CalculateCoverageRequest], - typing.Union[ + Union[ test_case.CalculateCoverageResponse, - typing.Awaitable[test_case.CalculateCoverageResponse], + Awaitable[test_case.CalculateCoverageResponse], ], ]: raise NotImplementedError() @@ -244,32 +304,41 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ImportTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def export_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ExportTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def list_test_case_results( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ListTestCaseResultsRequest], - typing.Union[ + Union[ test_case.ListTestCaseResultsResponse, - typing.Awaitable[test_case.ListTestCaseResultsResponse], + Awaitable[test_case.ListTestCaseResultsResponse], ], ]: raise NotImplementedError() + @property + def get_test_case_result( + self, + ) -> Callable[ + [test_case.GetTestCaseResultRequest], + Union[test_case.TestCaseResult, Awaitable[test_case.TestCaseResult]], + ]: + raise NotImplementedError() + __all__ = ("TestCasesTransport",) 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 a3b40f14..79b0442a 100644 --- a/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/test_cases/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import TestCasesTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -112,7 +110,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -120,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -191,24 +172,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -216,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -239,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -298,7 +271,7 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> Callable[[test_case.BatchDeleteTestCasesRequest], empty.Empty]: + ) -> Callable[[test_case.BatchDeleteTestCasesRequest], empty_pb2.Empty]: r"""Return a callable for the batch delete test cases method over gRPC. Batch deletes test cases. @@ -317,7 +290,7 @@ def batch_delete_test_cases( self._stubs["batch_delete_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases", request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["batch_delete_test_cases"] @@ -402,7 +375,7 @@ def update_test_case( @property def run_test_case( self, - ) -> Callable[[test_case.RunTestCaseRequest], operations.Operation]: + ) -> Callable[[test_case.RunTestCaseRequest], operations_pb2.Operation]: r"""Return a callable for the run test case method over gRPC. Kicks off a test case run. @@ -421,14 +394,14 @@ def run_test_case( self._stubs["run_test_case"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase", request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_test_case"] @property def batch_run_test_cases( self, - ) -> Callable[[test_case.BatchRunTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.BatchRunTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the batch run test cases method over gRPC. Kicks off a batch run of test cases. @@ -447,7 +420,7 @@ def batch_run_test_cases( self._stubs["batch_run_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases", request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_run_test_cases"] @@ -482,7 +455,7 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> Callable[[test_case.ImportTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.ImportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the import test cases method over gRPC. Imports the test cases from a Cloud Storage bucket or @@ -504,14 +477,14 @@ def import_test_cases( self._stubs["import_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases", request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_test_cases"] @property def export_test_cases( self, - ) -> Callable[[test_case.ExportTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.ExportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the export test cases method over gRPC. Exports the test cases under the agent to a Cloud @@ -532,7 +505,7 @@ def export_test_cases( self._stubs["export_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases", request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_test_cases"] @@ -564,5 +537,31 @@ def list_test_case_results( ) return self._stubs["list_test_case_results"] + @property + def get_test_case_result( + self, + ) -> Callable[[test_case.GetTestCaseResultRequest], test_case.TestCaseResult]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + ~.TestCaseResult]: + 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_test_case_result" not in self._stubs: + self._stubs["get_test_case_result"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult", + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs["get_test_case_result"] + __all__ = ("TestCasesGrpcTransport",) 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 b4e3c9fb..a1bb484d 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import test_case from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import TestCasesTransport, DEFAULT_CLIENT_INFO from .grpc import TestCasesGrpcTransport @@ -59,7 +56,7 @@ class TestCasesGrpcAsyncIOTransport(TestCasesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -67,7 +64,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -145,10 +145,10 @@ def __init__( 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 + 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: @@ -157,7 +157,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -165,70 +168,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -236,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -306,7 +278,7 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> Callable[[test_case.BatchDeleteTestCasesRequest], Awaitable[empty.Empty]]: + ) -> Callable[[test_case.BatchDeleteTestCasesRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the batch delete test cases method over gRPC. Batch deletes test cases. @@ -325,7 +297,7 @@ def batch_delete_test_cases( self._stubs["batch_delete_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/BatchDeleteTestCases", request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["batch_delete_test_cases"] @@ -414,7 +386,7 @@ def update_test_case( @property def run_test_case( self, - ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations.Operation]]: + ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the run test case method over gRPC. Kicks off a test case run. @@ -433,7 +405,7 @@ def run_test_case( self._stubs["run_test_case"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/RunTestCase", request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_test_case"] @@ -441,7 +413,7 @@ def run_test_case( def batch_run_test_cases( self, ) -> Callable[ - [test_case.BatchRunTestCasesRequest], Awaitable[operations.Operation] + [test_case.BatchRunTestCasesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch run test cases method over gRPC. @@ -461,7 +433,7 @@ def batch_run_test_cases( self._stubs["batch_run_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/BatchRunTestCases", request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_run_test_cases"] @@ -497,7 +469,9 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> Callable[[test_case.ImportTestCasesRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [test_case.ImportTestCasesRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the import test cases method over gRPC. Imports the test cases from a Cloud Storage bucket or @@ -519,14 +493,16 @@ def import_test_cases( self._stubs["import_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/ImportTestCases", request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_test_cases"] @property def export_test_cases( self, - ) -> Callable[[test_case.ExportTestCasesRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [test_case.ExportTestCasesRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the export test cases method over gRPC. Exports the test cases under the agent to a Cloud @@ -547,7 +523,7 @@ def export_test_cases( self._stubs["export_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TestCases/ExportTestCases", request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_test_cases"] @@ -580,5 +556,33 @@ def list_test_case_results( ) return self._stubs["list_test_case_results"] + @property + def get_test_case_result( + self, + ) -> Callable[ + [test_case.GetTestCaseResultRequest], Awaitable[test_case.TestCaseResult] + ]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + Awaitable[~.TestCaseResult]]: + 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_test_case_result" not in self._stubs: + self._stubs["get_test_case_result"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3.TestCases/GetTestCaseResult", + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs["get_test_case_result"] + __all__ = ("TestCasesGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py index af48a31a..c5098c8b 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TransitionRouteGroupsClient from .async_client import TransitionRouteGroupsAsyncClient 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 7ce59b75..49feee70 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.transition_route_groups import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport from .client import TransitionRouteGroupsClient @@ -65,31 +62,26 @@ class TransitionRouteGroupsAsyncClient: ) webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) - common_billing_account_path = staticmethod( TransitionRouteGroupsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TransitionRouteGroupsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) parse_common_folder_path = staticmethod( TransitionRouteGroupsClient.parse_common_folder_path ) - common_organization_path = staticmethod( TransitionRouteGroupsClient.common_organization_path ) parse_common_organization_path = staticmethod( TransitionRouteGroupsClient.parse_common_organization_path ) - common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) parse_common_project_path = staticmethod( TransitionRouteGroupsClient.parse_common_project_path ) - common_location_path = staticmethod( TransitionRouteGroupsClient.common_location_path ) @@ -99,7 +91,8 @@ class TransitionRouteGroupsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -114,7 +107,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -131,7 +124,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TransitionRouteGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TransitionRouteGroupsTransport: The transport used by the client instance. @@ -146,12 +139,12 @@ def transport(self) -> TransitionRouteGroupsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the transition route groups client. + """Instantiates the transition route groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -183,7 +176,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TransitionRouteGroupsClient( credentials=credentials, transport=transport, @@ -215,7 +207,6 @@ async def list_transition_route_groups( 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. @@ -245,7 +236,6 @@ async def list_transition_route_groups( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -300,7 +290,6 @@ async def get_transition_route_group( 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. @@ -329,7 +318,6 @@ async def get_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -387,7 +375,6 @@ async def create_transition_route_group( This corresponds to the ``transition_route_group`` 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. @@ -416,7 +403,6 @@ async def create_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if transition_route_group is not None: @@ -447,7 +433,7 @@ async def update_transition_route_group( request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -473,7 +459,6 @@ async def update_transition_route_group( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -502,7 +487,6 @@ async def update_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if transition_route_group is not None: request.transition_route_group = transition_route_group if update_mask is not None: @@ -555,7 +539,6 @@ async def delete_transition_route_group( 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. @@ -576,7 +559,6 @@ async def delete_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 cefa3935..44903604 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,8 +36,7 @@ from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TransitionRouteGroupsGrpcTransport from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class TransitionRouteGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TransitionRouteGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,23 +156,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TransitionRouteGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TransitionRouteGroupsTransport: The transport used by the client instance. + TransitionRouteGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -182,14 +182,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -200,14 +200,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -218,7 +218,7 @@ def parse_page_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -229,7 +229,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -238,14 +238,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -254,7 +254,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -267,7 +267,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -278,7 +278,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -289,7 +289,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -300,7 +300,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -314,12 +314,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TransitionRouteGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the transition route groups client. + """Instantiates the transition route groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -374,9 +374,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -388,12 +389,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -408,8 +411,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -448,7 +451,6 @@ def list_transition_route_groups( 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. @@ -482,10 +484,8 @@ def list_transition_route_groups( request, transition_route_group.ListTransitionRouteGroupsRequest ): request = transition_route_group.ListTransitionRouteGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -538,7 +538,6 @@ def get_transition_route_group( 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. @@ -571,10 +570,8 @@ def get_transition_route_group( request, transition_route_group.GetTransitionRouteGroupRequest ): request = transition_route_group.GetTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -630,7 +627,6 @@ def create_transition_route_group( This corresponds to the ``transition_route_group`` 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. @@ -665,10 +661,8 @@ def create_transition_route_group( request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if transition_route_group is not None: @@ -697,7 +691,7 @@ def update_transition_route_group( request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -723,7 +717,6 @@ def update_transition_route_group( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -758,10 +751,8 @@ def update_transition_route_group( request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if transition_route_group is not None: request.transition_route_group = transition_route_group if update_mask is not None: @@ -812,7 +803,6 @@ def delete_transition_route_group( 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. @@ -837,10 +827,8 @@ def delete_transition_route_group( request, transition_route_group.DeleteTransitionRouteGroupRequest ): request = transition_route_group.DeleteTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py index a5d2d6c6..2f302be6 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -121,7 +119,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py index eb2e1618..1f1275f6 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 8d8ec683..3a538d56 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import transition_route_group from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TransitionRouteGroupsTransport(abc.ABC): """Abstract transport class for TransitionRouteGroups.""" @@ -50,21 +60,24 @@ class TransitionRouteGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_transition_route_groups( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.ListTransitionRouteGroupsRequest], - typing.Union[ + Union[ transition_route_group.ListTransitionRouteGroupsResponse, - typing.Awaitable[transition_route_group.ListTransitionRouteGroupsResponse], + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_transition_route_groups( @property def get_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.GetTransitionRouteGroupRequest], - typing.Union[ + Union[ transition_route_group.TransitionRouteGroup, - typing.Awaitable[transition_route_group.TransitionRouteGroup], + Awaitable[transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_transition_route_group( @property def create_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - typing.Union[ + Union[ gcdc_transition_route_group.TransitionRouteGroup, - typing.Awaitable[gcdc_transition_route_group.TransitionRouteGroup], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_transition_route_group( @property def update_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - typing.Union[ + Union[ gcdc_transition_route_group.TransitionRouteGroup, - typing.Awaitable[gcdc_transition_route_group.TransitionRouteGroup], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_transition_route_group( @property def delete_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.DeleteTransitionRouteGroupRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py index a46694ea..8e38881e 100644 --- a/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/transition_route_groups/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,9 @@ def __init__( 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) @@ -119,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,23 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -382,7 +355,7 @@ def update_transition_route_group( def delete_transition_route_group( self, ) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], empty.Empty + [transition_route_group.DeleteTransitionRouteGroupRequest], empty_pb2.Empty ]: r"""Return a callable for the delete transition route group method over gRPC. @@ -405,7 +378,7 @@ def delete_transition_route_group( ] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup", request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_transition_route_group"] 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 76a4d328..58e0ce08 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .grpc import TransitionRouteGroupsGrpcTransport @@ -58,7 +55,7 @@ class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -387,7 +359,7 @@ def delete_transition_route_group( self, ) -> Callable[ [transition_route_group.DeleteTransitionRouteGroupRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete transition route group method over gRPC. @@ -410,7 +382,7 @@ def delete_transition_route_group( ] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.TransitionRouteGroups/DeleteTransitionRouteGroup", request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_transition_route_group"] diff --git a/google/cloud/dialogflowcx_v3/services/versions/__init__.py b/google/cloud/dialogflowcx_v3/services/versions/__init__.py index 93418cef..586be181 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/versions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import VersionsClient from .async_client import VersionsAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/versions/async_client.py b/google/cloud/dialogflowcx_v3/services/versions/async_client.py index 61aaec83..b702dbd3 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/versions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,11 +32,10 @@ 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 -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport from .client import VersionsClient @@ -56,31 +53,27 @@ class VersionsAsyncClient: version_path = staticmethod(VersionsClient.version_path) parse_version_path = staticmethod(VersionsClient.parse_version_path) - common_billing_account_path = staticmethod( VersionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( VersionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(VersionsClient.common_folder_path) parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(VersionsClient.common_organization_path) parse_common_organization_path = staticmethod( VersionsClient.parse_common_organization_path ) - common_project_path = staticmethod(VersionsClient.common_project_path) parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) - common_location_path = staticmethod(VersionsClient.common_location_path) parse_common_location_path = staticmethod(VersionsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: VersionsTransport: The transport used by the client instance. @@ -126,12 +119,12 @@ def transport(self) -> VersionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, VersionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = VersionsClient( credentials=credentials, transport=transport, @@ -195,7 +187,6 @@ async def list_versions( 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. @@ -225,7 +216,6 @@ async def list_versions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -280,7 +270,6 @@ async def get_version( 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. @@ -305,7 +294,6 @@ async def get_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -361,7 +349,6 @@ async def create_version( This corresponds to the ``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. @@ -391,7 +378,6 @@ async def create_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if version is not None: @@ -430,7 +416,7 @@ async def update_version( request: gcdc_version.UpdateVersionRequest = None, *, version: gcdc_version.Version = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -455,7 +441,6 @@ async def update_version( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -480,7 +465,6 @@ async def update_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if version is not None: request.version = version if update_mask is not None: @@ -533,7 +517,6 @@ async def delete_version( 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. @@ -554,7 +537,6 @@ async def delete_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -586,7 +568,8 @@ async def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Loads a specified version to draft version. + r"""Loads resources in the specified version to the draft + flow. Args: request (:class:`google.cloud.dialogflowcx_v3.types.LoadVersionRequest`): @@ -595,13 +578,12 @@ async def load_version( name (:class:`str`): Required. The [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft version. Format: + loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. 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. @@ -641,7 +623,6 @@ async def load_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -666,8 +647,8 @@ async def load_version( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflowcx_v3/services/versions/client.py b/google/cloud/dialogflowcx_v3/services/versions/client.py index 9ede0ecb..3463e8c4 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/client.py +++ b/google/cloud/dialogflowcx_v3/services/versions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,11 +36,10 @@ 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 -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import VersionsGrpcTransport from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class VersionsClientMeta(type): _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -86,7 +83,8 @@ class VersionsClient(metaclass=VersionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -120,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -137,7 +136,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -156,10 +155,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - VersionsTransport: The transport used by the client instance. + VersionsTransport: The transport used by the client + instance. """ return self._transport @@ -167,14 +167,14 @@ def transport(self) -> VersionsTransport: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -183,7 +183,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -196,7 +196,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -207,7 +207,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -229,7 +229,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -243,12 +243,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, VersionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -303,9 +303,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -317,12 +318,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -337,8 +340,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -377,7 +380,6 @@ def list_versions( 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. @@ -409,10 +411,8 @@ def list_versions( # there are no flattened fields. if not isinstance(request, version.ListVersionsRequest): request = version.ListVersionsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -463,7 +463,6 @@ def get_version( 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. @@ -490,10 +489,8 @@ def get_version( # there are no flattened fields. if not isinstance(request, version.GetVersionRequest): request = version.GetVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -545,7 +542,6 @@ def create_version( This corresponds to the ``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. @@ -577,10 +573,8 @@ def create_version( # there are no flattened fields. if not isinstance(request, gcdc_version.CreateVersionRequest): request = gcdc_version.CreateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if version is not None: @@ -615,7 +609,7 @@ def update_version( request: gcdc_version.UpdateVersionRequest = None, *, version: gcdc_version.Version = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -640,7 +634,6 @@ def update_version( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -667,10 +660,8 @@ def update_version( # there are no flattened fields. if not isinstance(request, gcdc_version.UpdateVersionRequest): request = gcdc_version.UpdateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if version is not None: request.version = version if update_mask is not None: @@ -719,7 +710,6 @@ def delete_version( 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. @@ -742,10 +732,8 @@ def delete_version( # there are no flattened fields. if not isinstance(request, version.DeleteVersionRequest): request = version.DeleteVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -773,7 +761,8 @@ def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Loads a specified version to draft version. + r"""Loads resources in the specified version to the draft + flow. Args: request (google.cloud.dialogflowcx_v3.types.LoadVersionRequest): @@ -782,13 +771,12 @@ def load_version( name (str): Required. The [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft version. Format: + loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. 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. @@ -830,10 +818,8 @@ def load_version( # there are no flattened fields. if not isinstance(request, version.LoadVersionRequest): request = version.LoadVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -854,8 +840,8 @@ def load_version( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflowcx_v3/services/versions/pagers.py b/google/cloud/dialogflowcx_v3/services/versions/pagers.py index 6c4592b9..1fdd561c 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/versions/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py index aa4c96b0..c5a42a0e 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/versions/transports/base.py b/google/cloud/dialogflowcx_v3/services/versions/transports/base.py index 3b08f675..596f71d1 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import version from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" @@ -50,21 +60,24 @@ class VersionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -141,56 +201,53 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_versions( self, - ) -> typing.Callable[ + ) -> Callable[ [version.ListVersionsRequest], - typing.Union[ - version.ListVersionsResponse, typing.Awaitable[version.ListVersionsResponse] - ], + Union[version.ListVersionsResponse, Awaitable[version.ListVersionsResponse]], ]: raise NotImplementedError() @property def get_version( self, - ) -> typing.Callable[ - [version.GetVersionRequest], - typing.Union[version.Version, typing.Awaitable[version.Version]], + ) -> Callable[ + [version.GetVersionRequest], Union[version.Version, Awaitable[version.Version]] ]: raise NotImplementedError() @property def create_version( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_version.CreateVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_version( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_version.UpdateVersionRequest], - typing.Union[gcdc_version.Version, typing.Awaitable[gcdc_version.Version]], + Union[gcdc_version.Version, Awaitable[gcdc_version.Version]], ]: raise NotImplementedError() @property def delete_version( self, - ) -> typing.Callable[ + ) -> Callable[ [version.DeleteVersionRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def load_version( self, - ) -> typing.Callable[ + ) -> Callable[ [version.LoadVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: 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 d3f5663f..55989b8a 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 version from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -323,7 +296,7 @@ def get_version(self) -> Callable[[version.GetVersionRequest], version.Version]: @property def create_version( self, - ) -> Callable[[gcdc_version.CreateVersionRequest], operations.Operation]: + ) -> Callable[[gcdc_version.CreateVersionRequest], operations_pb2.Operation]: r"""Return a callable for the create version method over gRPC. Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in @@ -343,7 +316,7 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/CreateVersion", request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @@ -375,7 +348,9 @@ def update_version( return self._stubs["update_version"] @property - def delete_version(self) -> Callable[[version.DeleteVersionRequest], empty.Empty]: + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], empty_pb2.Empty]: r"""Return a callable for the delete version method over gRPC. Deletes the specified @@ -395,17 +370,18 @@ def delete_version(self) -> Callable[[version.DeleteVersionRequest], empty.Empty self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/DeleteVersion", request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_version"] @property def load_version( self, - ) -> Callable[[version.LoadVersionRequest], operations.Operation]: + ) -> Callable[[version.LoadVersionRequest], operations_pb2.Operation]: r"""Return a callable for the load version method over gRPC. - Loads a specified version to draft version. + Loads resources in the specified version to the draft + flow. Returns: Callable[[~.LoadVersionRequest], @@ -421,7 +397,7 @@ def load_version( self._stubs["load_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/LoadVersion", request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["load_version"] 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 5fe47863..e61f15a6 100644 --- a/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/versions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import version from google.cloud.dialogflowcx_v3.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO from .grpc import VersionsGrpcTransport @@ -58,7 +55,7 @@ class VersionsGrpcAsyncIOTransport(VersionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -333,7 +305,9 @@ def get_version( @property def create_version( self, - ) -> Callable[[gcdc_version.CreateVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [gcdc_version.CreateVersionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create version method over gRPC. Creates a [Version][google.cloud.dialogflow.cx.v3.Version] in @@ -353,7 +327,7 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/CreateVersion", request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @@ -387,7 +361,7 @@ def update_version( @property def delete_version( self, - ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty.Empty]]: + ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete version method over gRPC. Deletes the specified @@ -407,17 +381,18 @@ def delete_version( self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/DeleteVersion", request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_version"] @property def load_version( self, - ) -> Callable[[version.LoadVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[[version.LoadVersionRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the load version method over gRPC. - Loads a specified version to draft version. + Loads resources in the specified version to the draft + flow. Returns: Callable[[~.LoadVersionRequest], @@ -433,7 +408,7 @@ def load_version( self._stubs["load_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Versions/LoadVersion", request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["load_version"] diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py b/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py index 2483e3be..28308a0b 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import WebhooksClient from .async_client import WebhooksAsyncClient diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py b/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py index 8420ed10..73db98ef 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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.services.webhooks import pagers from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport from .client import WebhooksClient @@ -49,33 +46,31 @@ class WebhooksAsyncClient: DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT + service_path = staticmethod(WebhooksClient.service_path) + parse_service_path = staticmethod(WebhooksClient.parse_service_path) webhook_path = staticmethod(WebhooksClient.webhook_path) parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) - common_billing_account_path = staticmethod( WebhooksClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( WebhooksClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(WebhooksClient.common_folder_path) parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) - common_organization_path = staticmethod(WebhooksClient.common_organization_path) parse_common_organization_path = staticmethod( WebhooksClient.parse_common_organization_path ) - common_project_path = staticmethod(WebhooksClient.common_project_path) parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) - common_location_path = staticmethod(WebhooksClient.common_location_path) parse_common_location_path = staticmethod(WebhooksClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +85,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -107,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> WebhooksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: WebhooksTransport: The transport used by the client instance. @@ -121,12 +116,12 @@ def transport(self) -> WebhooksTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, WebhooksTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the webhooks client. + """Instantiates the webhooks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -158,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = WebhooksClient( credentials=credentials, transport=transport, @@ -189,7 +183,6 @@ async def list_webhooks( 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. @@ -219,7 +212,6 @@ async def list_webhooks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -271,7 +263,6 @@ async def get_webhook( 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. @@ -303,7 +294,6 @@ async def get_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -355,7 +345,6 @@ async def create_webhook( This corresponds to the ``webhook`` 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. @@ -387,7 +376,6 @@ async def create_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if webhook is not None: @@ -418,7 +406,7 @@ async def update_webhook( request: gcdc_webhook.UpdateWebhookRequest = None, *, webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -442,7 +430,6 @@ async def update_webhook( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -474,7 +461,6 @@ async def update_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if webhook is not None: request.webhook = webhook if update_mask is not None: @@ -524,7 +510,6 @@ async def delete_webhook( 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. @@ -545,7 +530,6 @@ async def delete_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/client.py b/google/cloud/dialogflowcx_v3/services/webhooks/client.py index a1da5e3b..ac957258 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/client.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,9 +33,8 @@ 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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO from .transports.grpc import WebhooksGrpcTransport from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class WebhooksClientMeta(type): _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[WebhooksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class WebhooksClient(metaclass=WebhooksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,40 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> WebhooksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - WebhooksTransport: The transport used by the client instance. + WebhooksTransport: The transport used by the client + instance. """ return self._transport + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -176,7 +192,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -189,7 +205,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -200,7 +216,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -211,7 +227,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -222,7 +238,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -236,12 +252,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, WebhooksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the webhooks client. + """Instantiates the webhooks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -296,9 +312,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -310,12 +327,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -330,8 +349,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -369,7 +388,6 @@ def list_webhooks( 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. @@ -401,10 +419,8 @@ def list_webhooks( # there are no flattened fields. if not isinstance(request, webhook.ListWebhooksRequest): request = webhook.ListWebhooksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -452,7 +468,6 @@ def get_webhook( 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. @@ -486,10 +501,8 @@ def get_webhook( # there are no flattened fields. if not isinstance(request, webhook.GetWebhookRequest): request = webhook.GetWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -537,7 +550,6 @@ def create_webhook( This corresponds to the ``webhook`` 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. @@ -571,10 +583,8 @@ def create_webhook( # there are no flattened fields. if not isinstance(request, gcdc_webhook.CreateWebhookRequest): request = gcdc_webhook.CreateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if webhook is not None: @@ -601,7 +611,7 @@ def update_webhook( request: gcdc_webhook.UpdateWebhookRequest = None, *, webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -625,7 +635,6 @@ def update_webhook( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -659,10 +668,8 @@ def update_webhook( # there are no flattened fields. if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): request = gcdc_webhook.UpdateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if webhook is not None: request.webhook = webhook if update_mask is not None: @@ -708,7 +715,6 @@ def delete_webhook( 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. @@ -731,10 +737,8 @@ def delete_webhook( # there are no flattened fields. if not isinstance(request, webhook.DeleteWebhookRequest): request = webhook.DeleteWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py b/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py index b1738d62..009da9d5 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py b/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py index de5771fe..17f318f9 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py b/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py index 9cebd85a..1ececbf7 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class WebhooksTransport(abc.ABC): """Abstract transport class for Webhooks.""" @@ -48,21 +58,24 @@ class WebhooksTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,47 +191,44 @@ def _prep_wrapped_messages(self, client_info): @property def list_webhooks( self, - ) -> typing.Callable[ + ) -> Callable[ [webhook.ListWebhooksRequest], - typing.Union[ - webhook.ListWebhooksResponse, typing.Awaitable[webhook.ListWebhooksResponse] - ], + Union[webhook.ListWebhooksResponse, Awaitable[webhook.ListWebhooksResponse]], ]: raise NotImplementedError() @property def get_webhook( self, - ) -> typing.Callable[ - [webhook.GetWebhookRequest], - typing.Union[webhook.Webhook, typing.Awaitable[webhook.Webhook]], + ) -> Callable[ + [webhook.GetWebhookRequest], Union[webhook.Webhook, Awaitable[webhook.Webhook]] ]: raise NotImplementedError() @property def create_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_webhook.CreateWebhookRequest], - typing.Union[gcdc_webhook.Webhook, typing.Awaitable[gcdc_webhook.Webhook]], + Union[gcdc_webhook.Webhook, Awaitable[gcdc_webhook.Webhook]], ]: raise NotImplementedError() @property def update_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_webhook.UpdateWebhookRequest], - typing.Union[gcdc_webhook.Webhook, typing.Awaitable[gcdc_webhook.Webhook]], + Union[gcdc_webhook.Webhook, Awaitable[gcdc_webhook.Webhook]], ]: raise NotImplementedError() @property def delete_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [webhook.DeleteWebhookRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py b/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py index 31c25e97..7ce092c6 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import WebhooksTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +328,9 @@ def update_webhook( return self._stubs["update_webhook"] @property - def delete_webhook(self) -> Callable[[webhook.DeleteWebhookRequest], empty.Empty]: + def delete_webhook( + self, + ) -> Callable[[webhook.DeleteWebhookRequest], empty_pb2.Empty]: r"""Return a callable for the delete webhook method over gRPC. Deletes the specified webhook. @@ -374,7 +349,7 @@ def delete_webhook(self) -> Callable[[webhook.DeleteWebhookRequest], empty.Empty self._stubs["delete_webhook"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook", request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_webhook"] 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 4e556df5..7947152f 100644 --- a/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3/services/webhooks/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3.types import webhook from google.cloud.dialogflowcx_v3.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import WebhooksTransport, DEFAULT_CLIENT_INFO from .grpc import WebhooksGrpcTransport @@ -56,7 +53,7 @@ class WebhooksGrpcAsyncIOTransport(WebhooksTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -365,7 +337,7 @@ def update_webhook( @property def delete_webhook( self, - ) -> Callable[[webhook.DeleteWebhookRequest], Awaitable[empty.Empty]]: + ) -> Callable[[webhook.DeleteWebhookRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete webhook method over gRPC. Deletes the specified webhook. @@ -384,7 +356,7 @@ def delete_webhook( self._stubs["delete_webhook"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3.Webhooks/DeleteWebhook", request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_webhook"] diff --git a/google/cloud/dialogflowcx_v3/types/__init__.py b/google/cloud/dialogflowcx_v3/types/__init__.py index 724959d2..00da5907 100644 --- a/google/cloud/dialogflowcx_v3/types/__init__.py +++ b/google/cloud/dialogflowcx_v3/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .agent import ( Agent, AgentValidationResult, @@ -78,10 +76,14 @@ from .flow import ( CreateFlowRequest, DeleteFlowRequest, + ExportFlowRequest, + ExportFlowResponse, Flow, FlowValidationResult, GetFlowRequest, GetFlowValidationResultRequest, + ImportFlowRequest, + ImportFlowResponse, ListFlowsRequest, ListFlowsResponse, NluSettings, @@ -165,6 +167,7 @@ ExportTestCasesRequest, ExportTestCasesResponse, GetTestCaseRequest, + GetTestCaseResultRequest, ImportTestCasesMetadata, ImportTestCasesRequest, ImportTestCasesResponse, @@ -278,10 +281,14 @@ "VersionVariants", "CreateFlowRequest", "DeleteFlowRequest", + "ExportFlowRequest", + "ExportFlowResponse", "Flow", "FlowValidationResult", "GetFlowRequest", "GetFlowValidationResultRequest", + "ImportFlowRequest", + "ImportFlowResponse", "ListFlowsRequest", "ListFlowsResponse", "NluSettings", @@ -353,6 +360,7 @@ "ExportTestCasesRequest", "ExportTestCasesResponse", "GetTestCaseRequest", + "GetTestCaseResultRequest", "ImportTestCasesMetadata", "ImportTestCasesRequest", "ImportTestCasesResponse", diff --git a/google/cloud/dialogflowcx_v3/types/agent.py b/google/cloud/dialogflowcx_v3/types/agent.py index 39a49923..52bec47e 100644 --- a/google/cloud/dialogflowcx_v3/types/agent.py +++ b/google/cloud/dialogflowcx_v3/types/agent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,14 +42,13 @@ class SpeechToTextSettings(proto.Message): r"""Settings related to speech recognition. - Attributes: enable_speech_adaptation (bool): Whether to use speech adaptation for speech recognition. """ - enable_speech_adaptation = proto.Field(proto.BOOL, number=1) + enable_speech_adaptation = proto.Field(proto.BOOL, number=1,) class Agent(proto.Message): @@ -88,6 +84,9 @@ class Agent(proto.Message): field cannot be set by the [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3.Agents.UpdateAgent] method. + supported_language_codes (Sequence[str]): + The list of all languages supported by the agent (except for + the ``default_language_code``). time_zone (str): Required. The time zone of the agent from the `time zone database `__, e.g., @@ -122,29 +121,20 @@ class Agent(proto.Message): enabled in detect intent requests. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - default_language_code = proto.Field(proto.STRING, number=3) - - time_zone = proto.Field(proto.STRING, number=5) - - description = proto.Field(proto.STRING, number=6) - - avatar_uri = proto.Field(proto.STRING, number=7) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + default_language_code = proto.Field(proto.STRING, number=3,) + supported_language_codes = proto.RepeatedField(proto.STRING, number=4,) + time_zone = proto.Field(proto.STRING, number=5,) + description = proto.Field(proto.STRING, number=6,) + avatar_uri = proto.Field(proto.STRING, number=7,) speech_to_text_settings = proto.Field( proto.MESSAGE, number=13, message="SpeechToTextSettings", ) - - start_flow = proto.Field(proto.STRING, number=16) - - security_settings = proto.Field(proto.STRING, number=17) - - enable_stackdriver_logging = proto.Field(proto.BOOL, number=18) - - enable_spell_correction = proto.Field(proto.BOOL, number=20) + start_flow = proto.Field(proto.STRING, number=16,) + security_settings = proto.Field(proto.STRING, number=17,) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=18,) + enable_spell_correction = proto.Field(proto.BOOL, number=20,) class ListAgentsRequest(proto.Message): @@ -163,11 +153,9 @@ class ListAgentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListAgentsResponse(proto.Message): @@ -189,8 +177,7 @@ def raw_page(self): return self agents = proto.RepeatedField(proto.MESSAGE, number=1, message="Agent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetAgentRequest(proto.Message): @@ -203,7 +190,7 @@ class GetAgentRequest(proto.Message): ``projects//locations//agents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateAgentRequest(proto.Message): @@ -218,8 +205,7 @@ class CreateAgentRequest(proto.Message): Required. The agent to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) agent = proto.Field(proto.MESSAGE, number=2, message="Agent",) @@ -237,8 +223,9 @@ class UpdateAgentRequest(proto.Message): """ agent = proto.Field(proto.MESSAGE, number=1, message="Agent",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteAgentRequest(proto.Message): @@ -251,7 +238,7 @@ class DeleteAgentRequest(proto.Message): ``projects//locations//agents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -268,11 +255,15 @@ class ExportAgentRequest(proto.Message): export the agent to. The format of this URI must be ``gs:///``. If left unspecified, the serialized agent is returned inline. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) + environment = proto.Field(proto.STRING, number=5,) class ExportAgentResponse(proto.Message): @@ -288,9 +279,8 @@ class ExportAgentResponse(proto.Message): Uncompressed raw byte content for agent. """ - agent_uri = proto.Field(proto.STRING, number=1, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=2, oneof="agent") + agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=2, oneof="agent",) class RestoreAgentRequest(proto.Message): @@ -308,13 +298,20 @@ class RestoreAgentRequest(proto.Message): ``gs:///``. agent_content (bytes): Uncompressed raw byte content for agent. + restore_option (google.cloud.dialogflowcx_v3.types.RestoreAgentRequest.RestoreOption): + Agent restore mode. If not specified, ``KEEP`` is assumed. """ - name = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") + class RestoreOption(proto.Enum): + r"""Restore option.""" + RESTORE_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + name = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) + restore_option = proto.Field(proto.ENUM, number=5, enum=RestoreOption,) class ValidateAgentRequest(proto.Message): @@ -330,9 +327,8 @@ class ValidateAgentRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class GetAgentValidationResultRequest(proto.Message): @@ -348,9 +344,8 @@ class GetAgentValidationResultRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class AgentValidationResult(proto.Message): @@ -366,8 +361,7 @@ class AgentValidationResult(proto.Message): Contains all flow validation results. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) flow_validation_results = proto.RepeatedField( proto.MESSAGE, number=2, message=flow.FlowValidationResult, ) diff --git a/google/cloud/dialogflowcx_v3/types/audio_config.py b/google/cloud/dialogflowcx_v3/types/audio_config.py index 6b3a01d7..dd0c5f6d 100644 --- a/google/cloud/dialogflowcx_v3/types/audio_config.py +++ b/google/cloud/dialogflowcx_v3/types/audio_config.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -92,7 +89,6 @@ class OutputAudioEncoding(proto.Enum): class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -119,13 +115,10 @@ class SpeechWordInfo(proto.Message): also not rely on it to always be provided. """ - word = proto.Field(proto.STRING, number=3) - - start_offset = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_offset = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - confidence = proto.Field(proto.FLOAT, number=4) + word = proto.Field(proto.STRING, number=3,) + start_offset = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_offset = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + confidence = proto.Field(proto.FLOAT, number=4,) class InputAudioConfig(proto.Message): @@ -185,23 +178,16 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - - model = proto.Field(proto.STRING, number=7) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) + model = proto.Field(proto.STRING, number=7,) model_variant = proto.Field(proto.ENUM, number=10, enum="SpeechModelVariant",) - - single_utterance = proto.Field(proto.BOOL, number=8) + single_utterance = proto.Field(proto.BOOL, number=8,) class VoiceSelectionParams(proto.Message): r"""Description of which voice to use for speech synthesis. - Attributes: name (str): Optional. The name of the voice. If not set, the service @@ -223,14 +209,12 @@ class VoiceSelectionParams(proto.Message): rather than failing the request. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) ssml_gender = proto.Field(proto.ENUM, number=2, enum="SsmlVoiceGender",) class SynthesizeSpeechConfig(proto.Message): r"""Configuration of how speech should be synthesized. - Attributes: speaking_rate (float): Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 @@ -264,14 +248,10 @@ class SynthesizeSpeechConfig(proto.Message): synthesized audio. """ - speaking_rate = proto.Field(proto.DOUBLE, number=1) - - pitch = proto.Field(proto.DOUBLE, number=2) - - volume_gain_db = proto.Field(proto.DOUBLE, number=3) - - effects_profile_id = proto.RepeatedField(proto.STRING, number=5) - + speaking_rate = proto.Field(proto.DOUBLE, number=1,) + pitch = proto.Field(proto.DOUBLE, number=2,) + volume_gain_db = proto.Field(proto.DOUBLE, number=3,) + effects_profile_id = proto.RepeatedField(proto.STRING, number=5,) voice = proto.Field(proto.MESSAGE, number=4, message="VoiceSelectionParams",) @@ -298,9 +278,7 @@ class OutputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="OutputAudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) synthesize_speech_config = proto.Field( proto.MESSAGE, number=3, message="SynthesizeSpeechConfig", ) diff --git a/google/cloud/dialogflowcx_v3/types/entity_type.py b/google/cloud/dialogflowcx_v3/types/entity_type.py index a78a4ea4..daca7bc8 100644 --- a/google/cloud/dialogflowcx_v3/types/entity_type.py +++ b/google/cloud/dialogflowcx_v3/types/entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -121,7 +118,6 @@ class AutoExpansionMode(proto.Enum): class Entity(proto.Message): r"""An **entity entry** for an associated entity type. - Attributes: value (str): Required. The primary value associated with this entity @@ -147,37 +143,28 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class ExcludedPhrase(proto.Message): r"""An excluded entity phrase that should not be matched. - Attributes: value (str): Required. The word or phrase to be excluded. """ - value = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) kind = proto.Field(proto.ENUM, number=3, enum=Kind,) - auto_expansion_mode = proto.Field(proto.ENUM, number=4, enum=AutoExpansionMode,) - entities = proto.RepeatedField(proto.MESSAGE, number=5, message=Entity,) - excluded_phrases = proto.RepeatedField( proto.MESSAGE, number=6, message=ExcludedPhrase, ) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) - - redact = proto.Field(proto.BOOL, number=9) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) + redact = proto.Field(proto.BOOL, number=9,) class ListEntityTypesRequest(proto.Message): @@ -209,13 +196,10 @@ class ListEntityTypesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListEntityTypesResponse(proto.Message): @@ -237,8 +221,7 @@ def raw_page(self): return self entity_types = proto.RepeatedField(proto.MESSAGE, number=1, message="EntityType",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEntityTypeRequest(proto.Message): @@ -264,9 +247,8 @@ class GetEntityTypeRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateEntityTypeRequest(proto.Message): @@ -293,11 +275,9 @@ class CreateEntityTypeRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type = proto.Field(proto.MESSAGE, number=2, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateEntityTypeRequest(proto.Message): @@ -324,10 +304,10 @@ class UpdateEntityTypeRequest(proto.Message): """ entity_type = proto.Field(proto.MESSAGE, number=1, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteEntityTypeRequest(proto.Message): @@ -354,9 +334,8 @@ class DeleteEntityTypeRequest(proto.Message): of the entity type will be removed). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/environment.py b/google/cloud/dialogflowcx_v3/types/environment.py index 1159996f..27453be9 100644 --- a/google/cloud/dialogflowcx_v3/types/environment.py +++ b/google/cloud/dialogflowcx_v3/types/environment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -73,7 +70,6 @@ class Environment(proto.Message): class VersionConfig(proto.Message): r"""Configuration for the version. - Attributes: version (str): Required. Format: projects//flows//versions/. """ - version = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) + version = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) version_configs = proto.RepeatedField( proto.MESSAGE, number=6, message=VersionConfig, ) - - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class ListEnvironmentsRequest(proto.Message): @@ -113,11 +105,9 @@ class ListEnvironmentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListEnvironmentsResponse(proto.Message): @@ -141,8 +131,7 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEnvironmentRequest(proto.Message): @@ -157,7 +146,7 @@ class GetEnvironmentRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateEnvironmentRequest(proto.Message): @@ -175,8 +164,7 @@ class CreateEnvironmentRequest(proto.Message): Required. The environment to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) @@ -193,8 +181,9 @@ class UpdateEnvironmentRequest(proto.Message): """ environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteEnvironmentRequest(proto.Message): @@ -209,7 +198,7 @@ class DeleteEnvironmentRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class LookupEnvironmentHistoryRequest(proto.Message): @@ -229,11 +218,9 @@ class LookupEnvironmentHistoryRequest(proto.Message): request. """ - name = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class LookupEnvironmentHistoryResponse(proto.Message): @@ -256,8 +243,7 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/experiment.py b/google/cloud/dialogflowcx_v3/types/experiment.py index dd64833c..95f3eaa2 100644 --- a/google/cloud/dialogflowcx_v3/types/experiment.py +++ b/google/cloud/dialogflowcx_v3/types/experiment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -43,7 +40,6 @@ class Experiment(proto.Message): r"""Represents an experiment in an environment. - Attributes: name (str): The name of the experiment. @@ -78,7 +74,11 @@ class Experiment(proto.Message): last_update_time (google.protobuf.timestamp_pb2.Timestamp): Last update time of this experiment. experiment_length (google.protobuf.duration_pb2.Duration): - Maximum number of days to run the experiment. + Maximum number of days to run the + experiment/rollout. If auto-rollout is not + enabled, default value and maximum will be 30 + days. If auto-rollout is enabled, default value + and maximum will be 6 days. variants_history (Sequence[google.cloud.dialogflowcx_v3.types.VariantsHistory]): The history of updates to the experiment variants. @@ -93,7 +93,6 @@ class State(proto.Enum): class Definition(proto.Message): r"""Definition of the experiment. - Attributes: condition (str): The condition defines which subset of sessions are selected @@ -106,8 +105,7 @@ class Definition(proto.Message): experiment. """ - condition = proto.Field(proto.STRING, number=1) - + condition = proto.Field(proto.STRING, number=1,) version_variants = proto.Field( proto.MESSAGE, number=2, oneof="variants", message="VersionVariants", ) @@ -159,17 +157,13 @@ class ConfidenceInterval(proto.Message): Upper bound of the interval. """ - confidence_level = proto.Field(proto.DOUBLE, number=1) - - ratio = proto.Field(proto.DOUBLE, number=2) - - lower_bound = proto.Field(proto.DOUBLE, number=3) - - upper_bound = proto.Field(proto.DOUBLE, number=4) + confidence_level = proto.Field(proto.DOUBLE, number=1,) + ratio = proto.Field(proto.DOUBLE, number=2,) + lower_bound = proto.Field(proto.DOUBLE, number=3,) + upper_bound = proto.Field(proto.DOUBLE, number=4,) class Metric(proto.Message): r"""Metric and corresponding confidence intervals. - Attributes: type_ (google.cloud.dialogflowcx_v3.types.Experiment.Result.MetricType): Ratio-based metric type. Only one of type or count_type is @@ -189,27 +183,22 @@ class Metric(proto.Message): type_ = proto.Field( proto.ENUM, number=1, enum="Experiment.Result.MetricType", ) - count_type = proto.Field( proto.ENUM, number=5, enum="Experiment.Result.CountType", ) - - ratio = proto.Field(proto.DOUBLE, number=2, oneof="value") - - count = proto.Field(proto.DOUBLE, number=4, oneof="value") - + ratio = proto.Field(proto.DOUBLE, number=2, oneof="value",) + count = proto.Field(proto.DOUBLE, number=4, oneof="value",) confidence_interval = proto.Field( proto.MESSAGE, number=3, message="Experiment.Result.ConfidenceInterval", ) class VersionMetrics(proto.Message): r"""Version variant and associated metrics. - Attributes: version (str): The name of the flow [Version][google.cloud.dialogflow.cx.v3.Version]. Format: - ``projects//locations//agents//flows//versions/``. + ``projects//locations//agents//flows//versions/``. metrics (Sequence[google.cloud.dialogflowcx_v3.types.Experiment.Result.Metric]): The metrics and corresponding confidence intervals in the inference result. @@ -218,48 +207,34 @@ class VersionMetrics(proto.Message): this version. """ - version = proto.Field(proto.STRING, number=1) - + version = proto.Field(proto.STRING, number=1,) metrics = proto.RepeatedField( proto.MESSAGE, number=2, message="Experiment.Result.Metric", ) - - session_count = proto.Field(proto.INT32, number=3) + session_count = proto.Field(proto.INT32, number=3,) version_metrics = proto.RepeatedField( proto.MESSAGE, number=1, message="Experiment.Result.VersionMetrics", ) - last_update_time = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) state = proto.Field(proto.ENUM, number=4, enum=State,) - definition = proto.Field(proto.MESSAGE, number=5, message=Definition,) - result = proto.Field(proto.MESSAGE, number=6, message=Result,) - - create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) last_update_time = proto.Field( - proto.MESSAGE, number=10, message=timestamp.Timestamp, + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, ) - experiment_length = proto.Field( - proto.MESSAGE, number=11, message=duration.Duration, + proto.MESSAGE, number=11, message=duration_pb2.Duration, ) - variants_history = proto.RepeatedField( proto.MESSAGE, number=12, message="VariantsHistory", ) @@ -267,7 +242,6 @@ class VersionMetrics(proto.Message): class VersionVariants(proto.Message): r"""A list of flow version variants. - Attributes: variants (Sequence[google.cloud.dialogflowcx_v3.types.VersionVariants.Variant]): A list of flow version variants. @@ -275,7 +249,6 @@ class VersionVariants(proto.Message): class Variant(proto.Message): r"""A single flow version with specified traffic allocation. - Attributes: version (str): The name of the flow version. Format: @@ -288,18 +261,15 @@ class Variant(proto.Message): Whether the variant is for the control group. """ - version = proto.Field(proto.STRING, number=1) - - traffic_allocation = proto.Field(proto.FLOAT, number=2) - - is_control_group = proto.Field(proto.BOOL, number=3) + version = proto.Field(proto.STRING, number=1,) + traffic_allocation = proto.Field(proto.FLOAT, number=2,) + is_control_group = proto.Field(proto.BOOL, number=3,) variants = proto.RepeatedField(proto.MESSAGE, number=1, message=Variant,) class VariantsHistory(proto.Message): r"""The history of variants update. - Attributes: version_variants (google.cloud.dialogflowcx_v3.types.VersionVariants): The flow versions as the variants. @@ -310,8 +280,7 @@ class VariantsHistory(proto.Message): version_variants = proto.Field( proto.MESSAGE, number=1, oneof="variants", message="VersionVariants", ) - - update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class ListExperimentsRequest(proto.Message): @@ -332,11 +301,9 @@ class ListExperimentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListExperimentsResponse(proto.Message): @@ -360,8 +327,7 @@ def raw_page(self): return self experiments = proto.RepeatedField(proto.MESSAGE, number=1, message="Experiment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetExperimentRequest(proto.Message): @@ -376,7 +342,7 @@ class GetExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateExperimentRequest(proto.Message): @@ -394,8 +360,7 @@ class CreateExperimentRequest(proto.Message): Required. The experiment to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) experiment = proto.Field(proto.MESSAGE, number=2, message="Experiment",) @@ -412,8 +377,9 @@ class UpdateExperimentRequest(proto.Message): """ experiment = proto.Field(proto.MESSAGE, number=1, message="Experiment",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteExperimentRequest(proto.Message): @@ -428,7 +394,7 @@ class DeleteExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class StartExperimentRequest(proto.Message): @@ -441,7 +407,7 @@ class StartExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class StopExperimentRequest(proto.Message): @@ -454,7 +420,7 @@ class StopExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/flow.py b/google/cloud/dialogflowcx_v3/types/flow.py index 391ce448..f26652e7 100644 --- a/google/cloud/dialogflowcx_v3/types/flow.py +++ b/google/cloud/dialogflowcx_v3/types/flow.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import validation_message -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -39,13 +36,16 @@ "ValidateFlowRequest", "GetFlowValidationResultRequest", "FlowValidationResult", + "ImportFlowRequest", + "ImportFlowResponse", + "ExportFlowRequest", + "ExportFlowResponse", }, ) class NluSettings(proto.Message): r"""Settings related to NLU. - Attributes: model_type (google.cloud.dialogflowcx_v3.types.NluSettings.ModelType): Indicates the type of NLU model. @@ -76,9 +76,7 @@ class ModelTrainingMode(proto.Enum): MODEL_TRAINING_MODE_MANUAL = 2 model_type = proto.Field(proto.ENUM, number=1, enum=ModelType,) - - classification_threshold = proto.Field(proto.FLOAT, number=3) - + classification_threshold = proto.Field(proto.FLOAT, number=3,) model_training_mode = proto.Field(proto.ENUM, number=4, enum=ModelTrainingMode,) @@ -146,24 +144,31 @@ class Flow(proto.Message): these handlers are evaluated on a first-match basis. The first one that matches the event get executed, with the rest being ignored. + transition_route_groups (Sequence[str]): + A flow's transition route group serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition route + groups][Page.transition_route_groups]. Transition route + groups defined in the page have higher priority than + those defined in the flow. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. nlu_settings (google.cloud.dialogflowcx_v3.types.NluSettings): NLU related settings of the flow. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=4, message=page.TransitionRoute, ) - event_handlers = proto.RepeatedField( proto.MESSAGE, number=10, message=page.EventHandler, ) - + transition_route_groups = proto.RepeatedField(proto.STRING, number=15,) nlu_settings = proto.Field(proto.MESSAGE, number=11, message="NluSettings",) @@ -181,7 +186,9 @@ class CreateFlowRequest(proto.Message): The language of the following fields in ``flow``: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -190,11 +197,9 @@ class CreateFlowRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) flow = proto.Field(proto.MESSAGE, number=2, message="Flow",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class DeleteFlowRequest(proto.Message): @@ -219,9 +224,8 @@ class DeleteFlowRequest(proto.Message): cleared). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class ListFlowsRequest(proto.Message): @@ -243,7 +247,9 @@ class ListFlowsRequest(proto.Message): language dependent: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -252,13 +258,10 @@ class ListFlowsRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - language_code = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + language_code = proto.Field(proto.STRING, number=4,) class ListFlowsResponse(proto.Message): @@ -280,8 +283,7 @@ def raw_page(self): return self flows = proto.RepeatedField(proto.MESSAGE, number=1, message="Flow",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetFlowRequest(proto.Message): @@ -297,7 +299,9 @@ class GetFlowRequest(proto.Message): are language dependent: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -306,9 +310,8 @@ class GetFlowRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class UpdateFlowRequest(proto.Message): @@ -325,7 +328,9 @@ class UpdateFlowRequest(proto.Message): The language of the following fields in ``flow``: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -335,10 +340,10 @@ class UpdateFlowRequest(proto.Message): """ flow = proto.Field(proto.MESSAGE, number=1, message="Flow",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - - language_code = proto.Field(proto.STRING, number=3) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field(proto.STRING, number=3,) class TrainFlowRequest(proto.Message): @@ -351,7 +356,7 @@ class TrainFlowRequest(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ValidateFlowRequest(proto.Message): @@ -367,9 +372,8 @@ class ValidateFlowRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class GetFlowValidationResultRequest(proto.Message): @@ -385,9 +389,8 @@ class GetFlowValidationResultRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class FlowValidationResult(proto.Message): @@ -404,13 +407,96 @@ class FlowValidationResult(proto.Message): Last time the flow was validated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) validation_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=validation_message.ValidationMessage, ) + update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + + +class ImportFlowRequest(proto.Message): + r"""The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + parent (str): + Required. The agent to import the flow into. Format: + ``projects//locations//agents/``. + flow_uri (str): + The `Google Cloud + Storage `__ URI to + import flow from. The format of this URI must be + ``gs:///``. + flow_content (bytes): + Uncompressed raw byte content for flow. + import_option (google.cloud.dialogflowcx_v3.types.ImportFlowRequest.ImportOption): + Flow import mode. If not specified, ``KEEP`` is assumed. + """ + + class ImportOption(proto.Enum): + r"""Import option.""" + IMPORT_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + parent = proto.Field(proto.STRING, number=1,) + flow_uri = proto.Field(proto.STRING, number=2, oneof="flow",) + flow_content = proto.Field(proto.BYTES, number=3, oneof="flow",) + import_option = proto.Field(proto.ENUM, number=4, enum=ImportOption,) + + +class ImportFlowResponse(proto.Message): + r"""The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3.Flows.ImportFlow]. + + Attributes: + flow (str): + The unique identifier of the new flow. Format: + ``projects//locations//agents//flows/``. + """ + + flow = proto.Field(proto.STRING, number=1,) + + +class ExportFlowRequest(proto.Message): + r"""The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + Attributes: + name (str): + Required. The name of the flow to export. Format: + ``projects//locations//agents//flows/``. + flow_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the flow to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized flow is returned inline. + include_referenced_flows (bool): + Optional. Whether to export flows referenced + by the specified flow. + """ + + name = proto.Field(proto.STRING, number=1,) + flow_uri = proto.Field(proto.STRING, number=2,) + include_referenced_flows = proto.Field(proto.BOOL, number=4,) + + +class ExportFlowResponse(proto.Message): + r"""The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3.Flows.ExportFlow]. + + 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]. + flow_content (bytes): + Uncompressed raw byte content for flow. + """ - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + flow_uri = proto.Field(proto.STRING, number=1, oneof="flow",) + flow_content = proto.Field(proto.BYTES, number=2, oneof="flow",) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/fulfillment.py b/google/cloud/dialogflowcx_v3/types/fulfillment.py index c0a3267e..a4cf0283 100644 --- a/google/cloud/dialogflowcx_v3/types/fulfillment.py +++ b/google/cloud/dialogflowcx_v3/types/fulfillment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import response_message -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -68,7 +65,6 @@ class Fulfillment(proto.Message): class SetParameterAction(proto.Message): r"""Setting a parameter value. - Attributes: parameter (str): Display name of the parameter. @@ -77,9 +73,8 @@ class SetParameterAction(proto.Message): clears the parameter. """ - parameter = proto.Field(proto.STRING, number=1) - - value = proto.Field(proto.MESSAGE, number=2, message=struct.Value,) + parameter = proto.Field(proto.STRING, number=1,) + value = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Value,) class ConditionalCases(proto.Message): r"""A list of cascading if-else conditions. Cases are mutually @@ -126,7 +121,6 @@ class CaseContent(proto.Message): oneof="cases_or_message", message=response_message.ResponseMessage, ) - additional_cases = proto.Field( proto.MESSAGE, number=2, @@ -134,8 +128,7 @@ class CaseContent(proto.Message): message="Fulfillment.ConditionalCases", ) - condition = proto.Field(proto.STRING, number=1) - + condition = proto.Field(proto.STRING, number=1,) case_content = proto.RepeatedField( proto.MESSAGE, number=2, @@ -149,15 +142,11 @@ class CaseContent(proto.Message): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=response_message.ResponseMessage, ) - - webhook = proto.Field(proto.STRING, number=2) - - tag = proto.Field(proto.STRING, number=3) - + webhook = proto.Field(proto.STRING, number=2,) + tag = proto.Field(proto.STRING, number=3,) set_parameter_actions = proto.RepeatedField( proto.MESSAGE, number=4, message=SetParameterAction, ) - conditional_cases = proto.RepeatedField( proto.MESSAGE, number=5, message=ConditionalCases, ) diff --git a/google/cloud/dialogflowcx_v3/types/intent.py b/google/cloud/dialogflowcx_v3/types/intent.py index 204013f7..76c3bd0a 100644 --- a/google/cloud/dialogflowcx_v3/types/intent.py +++ b/google/cloud/dialogflowcx_v3/types/intent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -91,12 +88,12 @@ class Intent(proto.Message): assigned to fallback intents act as negative examples that triggers no-match event. labels (Sequence[google.cloud.dialogflowcx_v3.types.Intent.LabelsEntry]): - Optional. The key/value metadata to label an intent. Labels - can contain lowercase letters, digits and the symbols '-' - and '_'. International characters are allowed, including - letters from unicase alphabets. Keys must start with a - letter. Keys and values can be no longer than 63 characters - and no more than 128 bytes. + The key/value metadata to label an intent. Labels can + contain lowercase letters, digits and the symbols '-' and + '_'. International characters are allowed, including letters + from unicase alphabets. Keys must start with a letter. Keys + and values can be no longer than 63 characters and no more + than 128 bytes. Prefix "sys." is reserved for Dialogflow defined labels. Currently allowed Dialogflow defined labels include: @@ -106,10 +103,10 @@ class Intent(proto.Message): "sys.head" means the intent is a head intent. "sys.contextual" means the intent is a contextual intent. description (str): - Optional. Human readable description for - better understanding an intent like its scope, - content, result etc. Maximum character limit: - 140 characters. + Human readable description for better + understanding an intent like its scope, content, + result etc. Maximum character limit: 140 + characters. """ class TrainingPhrase(proto.Message): @@ -151,7 +148,6 @@ class TrainingPhrase(proto.Message): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -163,21 +159,17 @@ class Part(proto.Message): phrase. """ - text = proto.Field(proto.STRING, number=1) - - parameter_id = proto.Field(proto.STRING, number=2) - - id = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + parameter_id = proto.Field(proto.STRING, number=2,) + id = proto.Field(proto.STRING, number=1,) parts = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.TrainingPhrase.Part", ) - - repeat_count = proto.Field(proto.INT32, number=3) + repeat_count = proto.Field(proto.INT32, number=3,) class Parameter(proto.Message): r"""Represents an intent parameter. - Attributes: id (str): Required. The unique identifier of the parameter. This field @@ -206,31 +198,21 @@ class Parameter(proto.Message): is enabled. """ - id = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - is_list = proto.Field(proto.BOOL, number=3) - - redact = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + id = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + is_list = proto.Field(proto.BOOL, number=3,) + redact = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=3, message=TrainingPhrase, ) - parameters = proto.RepeatedField(proto.MESSAGE, number=4, message=Parameter,) - - priority = proto.Field(proto.INT32, number=5) - - is_fallback = proto.Field(proto.BOOL, number=6) - - labels = proto.MapField(proto.STRING, proto.STRING, number=7) - - description = proto.Field(proto.STRING, number=8) + priority = proto.Field(proto.INT32, number=5,) + is_fallback = proto.Field(proto.BOOL, number=6,) + labels = proto.MapField(proto.STRING, proto.STRING, number=7,) + description = proto.Field(proto.STRING, number=8,) class ListIntentsRequest(proto.Message): @@ -263,15 +245,11 @@ class ListIntentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=5, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListIntentsResponse(proto.Message): @@ -293,8 +271,7 @@ def raw_page(self): return self intents = proto.RepeatedField(proto.MESSAGE, number=1, message="Intent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetIntentRequest(proto.Message): @@ -318,9 +295,8 @@ class GetIntentRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateIntentRequest(proto.Message): @@ -345,11 +321,9 @@ class CreateIntentRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intent = proto.Field(proto.MESSAGE, number=2, message="Intent",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateIntentRequest(proto.Message): @@ -376,10 +350,10 @@ class UpdateIntentRequest(proto.Message): """ intent = proto.Field(proto.MESSAGE, number=1, message="Intent",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteIntentRequest(proto.Message): @@ -392,7 +366,7 @@ class DeleteIntentRequest(proto.Message): ``projects//locations//agents//intents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/page.py b/google/cloud/dialogflowcx_v3/types/page.py index 64440566..99bbfc48 100644 --- a/google/cloud/dialogflowcx_v3/types/page.py +++ b/google/cloud/dialogflowcx_v3/types/page.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import fulfillment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -122,22 +119,16 @@ class Page(proto.Message): input. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) entry_fulfillment = proto.Field( proto.MESSAGE, number=7, message=fulfillment.Fulfillment, ) - form = proto.Field(proto.MESSAGE, number=4, message="Form",) - - transition_route_groups = proto.RepeatedField(proto.STRING, number=11) - + transition_route_groups = proto.RepeatedField(proto.STRING, number=11,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=9, message="TransitionRoute", ) - event_handlers = proto.RepeatedField( proto.MESSAGE, number=10, message="EventHandler", ) @@ -159,7 +150,6 @@ class Form(proto.Message): class Parameter(proto.Message): r"""Represents a form parameter. - Attributes: display_name (str): Required. The human-readable name of the @@ -250,26 +240,19 @@ class FillBehavior(proto.Message): initial_prompt_fulfillment = proto.Field( proto.MESSAGE, number=3, message=fulfillment.Fulfillment, ) - reprompt_event_handlers = proto.RepeatedField( proto.MESSAGE, number=5, message="EventHandler", ) - display_name = proto.Field(proto.STRING, number=1) - - required = proto.Field(proto.BOOL, number=2) - - entity_type = proto.Field(proto.STRING, number=3) - - is_list = proto.Field(proto.BOOL, number=4) - + display_name = proto.Field(proto.STRING, number=1,) + required = proto.Field(proto.BOOL, number=2,) + entity_type = proto.Field(proto.STRING, number=3,) + is_list = proto.Field(proto.BOOL, number=4,) fill_behavior = proto.Field( proto.MESSAGE, number=7, message="Form.Parameter.FillBehavior", ) - - default_value = proto.Field(proto.MESSAGE, number=9, message=struct.Value,) - - redact = proto.Field(proto.BOOL, number=11) + default_value = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Value,) + redact = proto.Field(proto.BOOL, number=11,) parameters = proto.RepeatedField(proto.MESSAGE, number=1, message=Parameter,) @@ -312,17 +295,13 @@ class EventHandler(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=6) - - event = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=6,) + event = proto.Field(proto.STRING, number=4,) trigger_fulfillment = proto.Field( proto.MESSAGE, number=5, message=fulfillment.Fulfillment, ) - - target_page = proto.Field(proto.STRING, number=2, oneof="target") - - target_flow = proto.Field(proto.STRING, number=3, oneof="target") + target_page = proto.Field(proto.STRING, number=2, oneof="target",) + target_flow = proto.Field(proto.STRING, number=3, oneof="target",) class TransitionRoute(proto.Message): @@ -382,19 +361,14 @@ class TransitionRoute(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=6) - - intent = proto.Field(proto.STRING, number=1) - - condition = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=6,) + intent = proto.Field(proto.STRING, number=1,) + condition = proto.Field(proto.STRING, number=2,) trigger_fulfillment = proto.Field( proto.MESSAGE, number=3, message=fulfillment.Fulfillment, ) - - target_page = proto.Field(proto.STRING, number=4, oneof="target") - - target_flow = proto.Field(proto.STRING, number=5, oneof="target") + target_page = proto.Field(proto.STRING, number=4, oneof="target",) + target_flow = proto.Field(proto.STRING, number=5, oneof="target",) class ListPagesRequest(proto.Message): @@ -410,12 +384,21 @@ class ListPagesRequest(proto.Message): language dependent: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -430,13 +413,10 @@ class ListPagesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListPagesResponse(proto.Message): @@ -458,8 +438,7 @@ def raw_page(self): return self pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetPageRequest(proto.Message): @@ -475,12 +454,21 @@ class GetPageRequest(proto.Message): are language dependent: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -489,9 +477,8 @@ class GetPageRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreatePageRequest(proto.Message): @@ -508,12 +495,21 @@ class CreatePageRequest(proto.Message): The language of the following fields in ``page``: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -522,11 +518,9 @@ class CreatePageRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) page = proto.Field(proto.MESSAGE, number=2, message="Page",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdatePageRequest(proto.Message): @@ -540,12 +534,21 @@ class UpdatePageRequest(proto.Message): The language of the following fields in ``page``: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -559,10 +562,10 @@ class UpdatePageRequest(proto.Message): """ page = proto.Field(proto.MESSAGE, number=1, message="Page",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeletePageRequest(proto.Message): @@ -587,9 +590,8 @@ class DeletePageRequest(proto.Message): cleared). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/response_message.py b/google/cloud/dialogflowcx_v3/types/response_message.py index 9b346bd2..d02b573f 100644 --- a/google/cloud/dialogflowcx_v3/types/response_message.py +++ b/google/cloud/dialogflowcx_v3/types/response_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -89,7 +86,6 @@ class ResponseMessage(proto.Message): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Required. A collection of text responses. @@ -100,9 +96,8 @@ class Text(proto.Message): Dialogflow request. """ - text = proto.RepeatedField(proto.STRING, number=1) - - allow_playback_interruption = proto.Field(proto.BOOL, number=2) + text = proto.RepeatedField(proto.STRING, number=1,) + allow_playback_interruption = proto.Field(proto.BOOL, number=2,) class LiveAgentHandoff(proto.Message): r"""Indicates that the conversation should be handed off to a live @@ -128,7 +123,7 @@ class LiveAgentHandoff(proto.Message): Dialogflow doesn't impose any structure on this. """ - metadata = proto.Field(proto.MESSAGE, number=1, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=1, message=struct_pb2.Struct,) class ConversationSuccess(proto.Message): r"""Indicates that the conversation succeeded, i.e., the bot handled the @@ -156,7 +151,7 @@ class ConversationSuccess(proto.Message): any structure on this. """ - metadata = proto.Field(proto.MESSAGE, number=1, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=1, message=struct_pb2.Struct,) class OutputAudioText(proto.Message): r"""A text or ssml response that is preferentially used for TTS @@ -176,17 +171,15 @@ class OutputAudioText(proto.Message): Dialogflow request. """ - text = proto.Field(proto.STRING, number=1, oneof="source") - - ssml = proto.Field(proto.STRING, number=2, oneof="source") - - allow_playback_interruption = proto.Field(proto.BOOL, number=3) + text = proto.Field(proto.STRING, number=1, oneof="source",) + ssml = proto.Field(proto.STRING, number=2, oneof="source",) + allow_playback_interruption = proto.Field(proto.BOOL, number=3,) class EndInteraction(proto.Message): r"""Indicates that interaction with the Dialogflow agent has ended. This message is generated by Dialogflow only and not supposed to be defined by the user. - """ + """ class PlayAudio(proto.Message): r"""Specifies an audio clip to be played by the client as part of @@ -204,9 +197,8 @@ class PlayAudio(proto.Message): Dialogflow request. """ - audio_uri = proto.Field(proto.STRING, number=1) - - allow_playback_interruption = proto.Field(proto.BOOL, number=2) + audio_uri = proto.Field(proto.STRING, number=1,) + allow_playback_interruption = proto.Field(proto.BOOL, number=2,) class MixedAudio(proto.Message): r"""Represents an audio message that is composed of both segments @@ -224,7 +216,6 @@ class MixedAudio(proto.Message): class Segment(proto.Message): r"""Represents one segment of audio. - Attributes: audio (bytes): Raw audio synthesized from the Dialogflow @@ -241,42 +232,33 @@ class Segment(proto.Message): Dialogflow request. """ - audio = proto.Field(proto.BYTES, number=1, oneof="content") - - uri = proto.Field(proto.STRING, number=2, oneof="content") - - allow_playback_interruption = proto.Field(proto.BOOL, number=3) + audio = proto.Field(proto.BYTES, number=1, oneof="content",) + uri = proto.Field(proto.STRING, number=2, oneof="content",) + allow_playback_interruption = proto.Field(proto.BOOL, number=3,) segments = proto.RepeatedField( proto.MESSAGE, number=1, message="ResponseMessage.MixedAudio.Segment", ) text = proto.Field(proto.MESSAGE, number=1, oneof="message", message=Text,) - payload = proto.Field( - proto.MESSAGE, number=2, oneof="message", message=struct.Struct, + proto.MESSAGE, number=2, oneof="message", message=struct_pb2.Struct, ) - conversation_success = proto.Field( proto.MESSAGE, number=9, oneof="message", message=ConversationSuccess, ) - output_audio_text = proto.Field( proto.MESSAGE, number=8, oneof="message", message=OutputAudioText, ) - live_agent_handoff = proto.Field( proto.MESSAGE, number=10, oneof="message", message=LiveAgentHandoff, ) - end_interaction = proto.Field( proto.MESSAGE, number=11, oneof="message", message=EndInteraction, ) - play_audio = proto.Field( proto.MESSAGE, number=12, oneof="message", message=PlayAudio, ) - mixed_audio = proto.Field( proto.MESSAGE, number=13, oneof="message", message=MixedAudio, ) diff --git a/google/cloud/dialogflowcx_v3/types/security_settings.py b/google/cloud/dialogflowcx_v3/types/security_settings.py index a029b2f6..cee26936 100644 --- a/google/cloud/dialogflowcx_v3/types/security_settings.py +++ b/google/cloud/dialogflowcx_v3/types/security_settings.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,7 +42,7 @@ class GetSecuritySettingsRequest(proto.Message): ``projects//locations//securitySettings/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateSecuritySettingsRequest(proto.Message): @@ -65,13 +62,13 @@ class UpdateSecuritySettingsRequest(proto.Message): security_settings = proto.Field( proto.MESSAGE, number=1, message="SecuritySettings", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class ListSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.ListSecuritySettings][]. - Attributes: parent (str): Required. The location to list all security settings for. @@ -84,16 +81,13 @@ class ListSecuritySettingsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSecuritySettingsResponse(proto.Message): r"""The response message for [SecuritySettings.ListSecuritySettings][]. - Attributes: security_settings (Sequence[google.cloud.dialogflowcx_v3.types.SecuritySettings]): The list of security settings. @@ -110,13 +104,11 @@ def raw_page(self): security_settings = proto.RepeatedField( proto.MESSAGE, number=1, message="SecuritySettings", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.CreateSecuritySettings][]. - Attributes: parent (str): Required. The location to create an @@ -127,8 +119,7 @@ class CreateSecuritySettingsRequest(proto.Message): Required. The security settings to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) security_settings = proto.Field( proto.MESSAGE, number=2, message="SecuritySettings", ) @@ -136,7 +127,6 @@ class CreateSecuritySettingsRequest(proto.Message): class DeleteSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. - Attributes: name (str): Required. The name of the @@ -145,7 +135,7 @@ class DeleteSecuritySettingsRequest(proto.Message): ``projects//locations//securitySettings/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class SecuritySettings(proto.Message): @@ -205,18 +195,12 @@ class PurgeDataType(proto.Enum): PURGE_DATA_TYPE_UNSPECIFIED = 0 DIALOGFLOW_HISTORY = 1 - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) redaction_strategy = proto.Field(proto.ENUM, number=3, enum=RedactionStrategy,) - redaction_scope = proto.Field(proto.ENUM, number=4, enum=RedactionScope,) - - inspect_template = proto.Field(proto.STRING, number=9) - - retention_window_days = proto.Field(proto.INT32, number=6, oneof="data_retention") - + inspect_template = proto.Field(proto.STRING, number=9,) + retention_window_days = proto.Field(proto.INT32, number=6, oneof="data_retention",) purge_data_types = proto.RepeatedField(proto.ENUM, number=8, enum=PurgeDataType,) diff --git a/google/cloud/dialogflowcx_v3/types/session.py b/google/cloud/dialogflowcx_v3/types/session.py index e452a707..683e1353 100644 --- a/google/cloud/dialogflowcx_v3/types/session.py +++ b/google/cloud/dialogflowcx_v3/types/session.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import audio_config from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent from google.cloud.dialogflowcx_v3.types import page from google.cloud.dialogflowcx_v3.types import response_message from google.cloud.dialogflowcx_v3.types import session_entity_type -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -57,7 +54,6 @@ class DetectIntentRequest(proto.Message): r"""The request to detect user's intent. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -86,12 +82,9 @@ class DetectIntentRequest(proto.Message): generate the output audio. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -99,7 +92,6 @@ class DetectIntentRequest(proto.Message): class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): Output only. The unique identifier of the @@ -126,12 +118,9 @@ class DetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - - output_audio = proto.Field(proto.BYTES, number=4) - + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) @@ -202,12 +191,9 @@ class StreamingDetectIntentRequest(proto.Message): generate the output audio. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -225,7 +211,13 @@ class StreamingDetectIntentResponse(proto.Message): what the user said. The last ``recognition_result`` has ``is_final`` set to ``true``. - 2. The last message contains ``detect_intent_response``. + 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``. Attributes: recognition_result (google.cloud.dialogflowcx_v3.types.StreamingRecognitionResult): @@ -237,7 +229,6 @@ class StreamingDetectIntentResponse(proto.Message): recognition_result = proto.Field( proto.MESSAGE, number=1, oneof="response", message="StreamingRecognitionResult", ) - detect_intent_response = proto.Field( proto.MESSAGE, number=2, oneof="response", message="DetectIntentResponse", ) @@ -328,25 +319,20 @@ class MessageType(proto.Enum): END_OF_SINGLE_UTTERANCE = 2 message_type = proto.Field(proto.ENUM, number=1, enum=MessageType,) - - transcript = proto.Field(proto.STRING, number=2) - - is_final = proto.Field(proto.BOOL, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - stability = proto.Field(proto.FLOAT, number=6) - + transcript = proto.Field(proto.STRING, number=2,) + is_final = proto.Field(proto.BOOL, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + stability = proto.Field(proto.FLOAT, number=6,) speech_word_info = proto.RepeatedField( proto.MESSAGE, number=7, message=audio_config.SpeechWordInfo, ) - - speech_end_offset = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) + speech_end_offset = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration, + ) class QueryParameters(proto.Message): r"""Represents the parameters of a conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -362,9 +348,20 @@ class QueryParameters(proto.Message): synonyms apply to all languages and persist for the session of this query. payload (google.protobuf.struct_pb2.Struct): - This field can be used to pass custom data - into the webhook associated with the agent. - Arbitrary JSON objects are supported. + This field can be used to pass custom data into the webhook + associated with the agent. Arbitrary JSON objects are + supported. Some integrations that query a Dialogflow agent + may provide additional information in the payload. In + particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + :: + + { + "telephony": { + "caller_id": "+18558363987" + } + } parameters (google.protobuf.struct_pb2.Struct): Additional parameters to be put into [session parameters][SessionInfo.parameters]. To remove a parameter @@ -390,6 +387,22 @@ class QueryParameters(proto.Message): from composite entity property names to property values - Else: parameter value + current_page (str): + The unique identifier of the + [page][google.cloud.dialogflow.cx.v3.Page] to override the + [current page][QueryResult.current_page] in the session. + Format: + ``projects//locations//agents//pages/``. + + If ``current_page`` is specified, the previous state of the + session will be ignored by Dialogflow, including the + [previous page][QueryResult.current_page] and the [previous + session parameters][QueryResult.parameters]. In most cases, + [current_page][google.cloud.dialogflow.cx.v3.QueryParameters.current_page] + and + [parameters][google.cloud.dialogflow.cx.v3.QueryParameters.parameters] + should be configured together to direct a session to a + specific state. disable_webhook (bool): Whether to disable webhook calls for this request. @@ -412,23 +425,17 @@ class QueryParameters(proto.Message): None-Match", "X-Forwarded-For", etc. """ - time_zone = proto.Field(proto.STRING, number=1) - - geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) - + time_zone = proto.Field(proto.STRING, number=1,) + geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=3, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - parameters = proto.Field(proto.MESSAGE, number=5, message=struct.Struct,) - - disable_webhook = proto.Field(proto.BOOL, number=7) - - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=8) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=10) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + parameters = proto.Field(proto.MESSAGE, number=5, message=struct_pb2.Struct,) + current_page = proto.Field(proto.STRING, number=6,) + disable_webhook = proto.Field(proto.BOOL, number=7,) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=8,) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=10,) class QueryInput(proto.Message): @@ -461,21 +468,15 @@ class QueryInput(proto.Message): """ text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - intent = proto.Field(proto.MESSAGE, number=3, oneof="input", message="IntentInput",) - audio = proto.Field(proto.MESSAGE, number=5, oneof="input", message="AudioInput",) - event = proto.Field(proto.MESSAGE, number=6, oneof="input", message="EventInput",) - dtmf = proto.Field(proto.MESSAGE, number=7, oneof="input", message="DtmfInput",) - - language_code = proto.Field(proto.STRING, number=4) + language_code = proto.Field(proto.STRING, number=4,) class QueryResult(proto.Message): r"""Represents the result of a conversational query. - Attributes: text (str): If [natural language @@ -484,12 +485,13 @@ class QueryResult(proto.Message): 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. + intent identifier. Format: + ``projects//locations//agents//intents/``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3.AudioInput] was - provided as input, this field will contain the trascript for - the audio. + provided as input, this field will contain the transcript + for the audio. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3.EventInput] was provided as input, this field will contain the name of the @@ -573,40 +575,26 @@ class QueryResult(proto.Message): specified in the request. """ - text = proto.Field(proto.STRING, number=1, oneof="query") - - trigger_intent = proto.Field(proto.STRING, number=11, oneof="query") - - transcript = proto.Field(proto.STRING, number=12, oneof="query") - - trigger_event = proto.Field(proto.STRING, number=14, oneof="query") - - language_code = proto.Field(proto.STRING, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) - + text = proto.Field(proto.STRING, number=1, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=11, oneof="query",) + transcript = proto.Field(proto.STRING, number=12, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=14, oneof="query",) + language_code = proto.Field(proto.STRING, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) response_messages = proto.RepeatedField( proto.MESSAGE, number=4, message=response_message.ResponseMessage, ) - webhook_statuses = proto.RepeatedField( - proto.MESSAGE, number=13, message=status.Status, + proto.MESSAGE, number=13, message=status_pb2.Status, ) - webhook_payloads = proto.RepeatedField( - proto.MESSAGE, number=6, message=struct.Struct, + proto.MESSAGE, number=6, message=struct_pb2.Struct, ) - current_page = proto.Field(proto.MESSAGE, number=7, message=page.Page,) - intent = proto.Field(proto.MESSAGE, number=8, message=gcdc_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=9) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=9,) match = proto.Field(proto.MESSAGE, number=15, message="Match",) - - diagnostic_info = proto.Field(proto.MESSAGE, number=10, message=struct.Struct,) - + diagnostic_info = proto.Field(proto.MESSAGE, number=10, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) @@ -614,7 +602,6 @@ class QueryResult(proto.Message): class TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -622,7 +609,7 @@ class TextInput(proto.Message): exceed 256 characters. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) class IntentInput(proto.Message): @@ -635,12 +622,11 @@ class IntentInput(proto.Message): ``projects//locations//agents//intents/``. """ - intent = proto.Field(proto.STRING, number=1) + intent = proto.Field(proto.STRING, number=1,) class AudioInput(proto.Message): r"""Represents the natural speech audio to be processed. - Attributes: config (google.cloud.dialogflowcx_v3.types.InputAudioConfig): Required. Instructs the speech recognizer how @@ -661,24 +647,21 @@ class AudioInput(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.InputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class EventInput(proto.Message): r"""Represents the event to trigger. - Attributes: event (str): Name of the event. """ - event = proto.Field(proto.STRING, number=1) + event = proto.Field(proto.STRING, number=1,) class DtmfInput(proto.Message): r"""Represents the input for dtmf event. - Attributes: digits (str): The dtmf digits. @@ -686,14 +669,12 @@ class DtmfInput(proto.Message): The finish digit (if any). """ - digits = proto.Field(proto.STRING, number=1) - - finish_digit = proto.Field(proto.STRING, number=2) + digits = proto.Field(proto.STRING, number=1,) + finish_digit = proto.Field(proto.STRING, number=2,) class Match(proto.Message): r"""Represents one match result of [MatchIntent][]. - Attributes: intent (google.cloud.dialogflowcx_v3.types.Intent): The [Intent][google.cloud.dialogflow.cx.v3.Intent] that @@ -756,21 +737,15 @@ class MatchType(proto.Enum): EVENT = 6 intent = proto.Field(proto.MESSAGE, number=1, message=gcdc_intent.Intent,) - - event = proto.Field(proto.STRING, number=6) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - resolved_input = proto.Field(proto.STRING, number=3) - + event = proto.Field(proto.STRING, number=6,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + resolved_input = proto.Field(proto.STRING, number=3,) match_type = proto.Field(proto.ENUM, number=4, enum=MatchType,) - - confidence = proto.Field(proto.FLOAT, number=5) + confidence = proto.Field(proto.FLOAT, number=5,) class MatchIntentRequest(proto.Message): r"""Request of [MatchIntent][]. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -792,16 +767,13 @@ class MatchIntentRequest(proto.Message): Required. The input specification. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) class MatchIntentResponse(proto.Message): r"""Response of [MatchIntent][]. - Attributes: text (str): If [natural language @@ -810,12 +782,13 @@ class MatchIntentResponse(proto.Message): 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. + intent identifier. Format: + ``projects//locations//agents//intents/``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3.AudioInput] was - provided as input, this field will contain the trascript for - the audio. + provided as input, this field will contain the transcript + for the audio. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3.EventInput] was provided as input, this field will contain a copy of the @@ -830,22 +803,16 @@ class MatchIntentResponse(proto.Message): but not limited to ``name`` and ``display_name``. """ - text = proto.Field(proto.STRING, number=1, oneof="query") - - trigger_intent = proto.Field(proto.STRING, number=2, oneof="query") - - transcript = proto.Field(proto.STRING, number=3, oneof="query") - - trigger_event = proto.Field(proto.STRING, number=6, oneof="query") - + text = proto.Field(proto.STRING, number=1, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=2, oneof="query",) + transcript = proto.Field(proto.STRING, number=3, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=6, oneof="query",) matches = proto.RepeatedField(proto.MESSAGE, number=4, message="Match",) - current_page = proto.Field(proto.MESSAGE, number=5, message=page.Page,) class FulfillIntentRequest(proto.Message): r"""Request of [FulfillIntent][] - Attributes: match_intent_request (google.cloud.dialogflowcx_v3.types.MatchIntentRequest): Must be same as the corresponding MatchIntent @@ -860,9 +827,7 @@ class FulfillIntentRequest(proto.Message): match_intent_request = proto.Field( proto.MESSAGE, number=1, message="MatchIntentRequest", ) - match = proto.Field(proto.MESSAGE, number=2, message="Match",) - output_audio_config = proto.Field( proto.MESSAGE, number=3, message=audio_config.OutputAudioConfig, ) @@ -870,7 +835,6 @@ class FulfillIntentRequest(proto.Message): class FulfillIntentResponse(proto.Message): r"""Response of [FulfillIntent][] - Attributes: response_id (str): Output only. The unique identifier of the @@ -897,12 +861,9 @@ class FulfillIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - - output_audio = proto.Field(proto.BYTES, number=3) - + output_audio = proto.Field(proto.BYTES, number=3,) output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -924,9 +885,8 @@ class SentimentAnalysisResult(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/session_entity_type.py b/google/cloud/dialogflowcx_v3/types/session_entity_type.py index ebdb3598..c2b427c4 100644 --- a/google/cloud/dialogflowcx_v3/types/session_entity_type.py +++ b/google/cloud/dialogflowcx_v3/types/session_entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import entity_type -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -77,10 +74,8 @@ class EntityOverrideMode(proto.Enum): ENTITY_OVERRIDE_MODE_OVERRIDE = 1 ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) entity_override_mode = proto.Field(proto.ENUM, number=3, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=4, message=entity_type.EntityType.Entity, ) @@ -107,11 +102,9 @@ class ListSessionEntityTypesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSessionEntityTypesResponse(proto.Message): @@ -136,8 +129,7 @@ def raw_page(self): session_entity_types = proto.RepeatedField( proto.MESSAGE, number=1, message="SessionEntityType", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetSessionEntityTypeRequest(proto.Message): @@ -154,7 +146,7 @@ class GetSessionEntityTypeRequest(proto.Message): 'draft' environment. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -174,8 +166,7 @@ class CreateSessionEntityTypeRequest(proto.Message): Required. The session entity type to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) session_entity_type = proto.Field( proto.MESSAGE, number=2, message="SessionEntityType", ) @@ -200,8 +191,9 @@ class UpdateSessionEntityTypeRequest(proto.Message): session_entity_type = proto.Field( proto.MESSAGE, number=1, message="SessionEntityType", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteSessionEntityTypeRequest(proto.Message): @@ -219,7 +211,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): 'draft' environment. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/test_case.py b/google/cloud/dialogflowcx_v3/types/test_case.py index 29037fd9..0d683454 100644 --- a/google/cloud/dialogflowcx_v3/types/test_case.py +++ b/google/cloud/dialogflowcx_v3/types/test_case.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3.types import intent as gcdc_intent from google.cloud.dialogflowcx_v3.types import page as gcdc_page from google.cloud.dialogflowcx_v3.types import response_message from google.cloud.dialogflowcx_v3.types import session from google.cloud.dialogflowcx_v3.types import transition_route_group -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -66,6 +63,7 @@ "ExportTestCasesMetadata", "ListTestCaseResultsRequest", "ListTestCaseResultsResponse", + "GetTestCaseResultRequest", }, ) @@ -79,7 +77,6 @@ class TestResult(proto.Enum): class TestCase(proto.Message): r"""Represents a test case. - Attributes: name (str): The unique identifier of the test case. @@ -112,22 +109,17 @@ class TestCase(proto.Message): The latest test result. """ - name = proto.Field(proto.STRING, number=1) - - tags = proto.RepeatedField(proto.STRING, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - notes = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + tags = proto.RepeatedField(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + notes = proto.Field(proto.STRING, number=4,) test_config = proto.Field(proto.MESSAGE, number=13, message="TestConfig",) - test_case_conversation_turns = proto.RepeatedField( proto.MESSAGE, number=5, message="ConversationTurn", ) - - creation_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + creation_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) last_test_result = proto.Field(proto.MESSAGE, number=12, message="TestCaseResult",) @@ -152,22 +144,17 @@ class TestCaseResult(proto.Message): The time that the test was run. """ - name = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) conversation_turns = proto.RepeatedField( proto.MESSAGE, number=3, message="ConversationTurn", ) - test_result = proto.Field(proto.ENUM, number=4, enum="TestResult",) - - test_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + test_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class TestConfig(proto.Message): r"""Represents configurations for a test case. - Attributes: tracking_parameters (Sequence[str]): Session parameters to be compared when @@ -178,9 +165,8 @@ class TestConfig(proto.Message): ``projects//locations//agents//flows/``. """ - tracking_parameters = proto.RepeatedField(proto.STRING, number=1) - - flow = proto.Field(proto.STRING, number=2) + tracking_parameters = proto.RepeatedField(proto.STRING, number=1,) + flow = proto.Field(proto.STRING, number=2,) class ConversationTurn(proto.Message): @@ -196,7 +182,6 @@ class ConversationTurn(proto.Message): class UserInput(proto.Message): r"""The input from the human user. - Attributes: input (google.cloud.dialogflowcx_v3.types.QueryInput): Supports [text @@ -216,16 +201,13 @@ class UserInput(proto.Message): """ input = proto.Field(proto.MESSAGE, number=5, message=session.QueryInput,) - injected_parameters = proto.Field( - proto.MESSAGE, number=2, message=struct.Struct, + proto.MESSAGE, number=2, message=struct_pb2.Struct, ) - - is_webhook_enabled = proto.Field(proto.BOOL, number=3) + is_webhook_enabled = proto.Field(proto.BOOL, number=3,) class VirtualAgentOutput(proto.Message): r"""The output from the virtual agent. - Attributes: session_parameters (google.protobuf.struct_pb2.Struct): The session parameters available to the bot @@ -256,29 +238,24 @@ class VirtualAgentOutput(proto.Message): """ session_parameters = proto.Field( - proto.MESSAGE, number=4, message=struct.Struct, + proto.MESSAGE, number=4, message=struct_pb2.Struct, ) - differences = proto.RepeatedField( proto.MESSAGE, number=5, message="TestRunDifference", ) - - diagnostic_info = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - + diagnostic_info = proto.Field( + proto.MESSAGE, number=6, message=struct_pb2.Struct, + ) triggered_intent = proto.Field( proto.MESSAGE, number=7, message=gcdc_intent.Intent, ) - current_page = proto.Field(proto.MESSAGE, number=8, message=gcdc_page.Page,) - text_responses = proto.RepeatedField( proto.MESSAGE, number=9, message=response_message.ResponseMessage.Text, ) - - status = proto.Field(proto.MESSAGE, number=10, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=10, message=status_pb2.Status,) user_input = proto.Field(proto.MESSAGE, number=1, message=UserInput,) - virtual_agent_output = proto.Field( proto.MESSAGE, number=2, message=VirtualAgentOutput, ) @@ -305,8 +282,7 @@ class DiffType(proto.Enum): UTTERANCE = 4 type_ = proto.Field(proto.ENUM, number=1, enum=DiffType,) - - description = proto.Field(proto.STRING, number=2) + description = proto.Field(proto.STRING, number=2,) class TransitionCoverage(proto.Message): @@ -325,7 +301,6 @@ class TransitionCoverage(proto.Message): class TransitionNode(proto.Message): r"""The source or target of a transition. - Attributes: page (google.cloud.dialogflowcx_v3.types.Page): Indicates a transition to a @@ -340,14 +315,12 @@ class TransitionNode(proto.Message): page = proto.Field( proto.MESSAGE, number=1, oneof="kind", message=gcdc_page.Page, ) - flow = proto.Field( proto.MESSAGE, number=2, oneof="kind", message=gcdc_flow.Flow, ) class Transition(proto.Message): r"""A transition in a page. - Attributes: source (google.cloud.dialogflowcx_v3.types.TransitionCoverage.TransitionNode): The start node of a transition. @@ -368,26 +341,20 @@ class Transition(proto.Message): source = proto.Field( proto.MESSAGE, number=1, message="TransitionCoverage.TransitionNode", ) - - index = proto.Field(proto.INT32, number=4) - + index = proto.Field(proto.INT32, number=4,) target = proto.Field( proto.MESSAGE, number=2, message="TransitionCoverage.TransitionNode", ) - - covered = proto.Field(proto.BOOL, number=3) - + covered = proto.Field(proto.BOOL, number=3,) transition_route = proto.Field( proto.MESSAGE, number=5, oneof="detail", message=gcdc_page.TransitionRoute, ) - event_handler = proto.Field( proto.MESSAGE, number=6, oneof="detail", message=gcdc_page.EventHandler, ) transitions = proto.RepeatedField(proto.MESSAGE, number=1, message=Transition,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class TransitionRouteGroupCoverage(proto.Message): @@ -406,7 +373,6 @@ class TransitionRouteGroupCoverage(proto.Message): class Coverage(proto.Message): r"""Coverage result message for one transition route group. - Attributes: route_group (google.cloud.dialogflowcx_v3.types.TransitionRouteGroup): Transition route group metadata. Only name @@ -421,7 +387,6 @@ class Coverage(proto.Message): class Transition(proto.Message): r"""A transition coverage in a transition route group. - Attributes: transition_route (google.cloud.dialogflowcx_v3.types.TransitionRoute): Intent route or condition route. @@ -434,26 +399,22 @@ class Transition(proto.Message): transition_route = proto.Field( proto.MESSAGE, number=1, message=gcdc_page.TransitionRoute, ) - - covered = proto.Field(proto.BOOL, number=2) + covered = proto.Field(proto.BOOL, number=2,) route_group = proto.Field( proto.MESSAGE, number=1, message=transition_route_group.TransitionRouteGroup, ) - transitions = proto.RepeatedField( proto.MESSAGE, number=2, message="TransitionRouteGroupCoverage.Coverage.Transition", ) - - coverage_score = proto.Field(proto.FLOAT, number=3) + coverage_score = proto.Field(proto.FLOAT, number=3,) coverages = proto.RepeatedField(proto.MESSAGE, number=1, message=Coverage,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class IntentCoverage(proto.Message): @@ -471,7 +432,6 @@ class IntentCoverage(proto.Message): class Intent(proto.Message): r"""The agent's intent. - Attributes: intent (str): The intent full resource name @@ -480,13 +440,11 @@ class Intent(proto.Message): least one of the agent's test cases. """ - intent = proto.Field(proto.STRING, number=1) - - covered = proto.Field(proto.BOOL, number=2) + intent = proto.Field(proto.STRING, number=1,) + covered = proto.Field(proto.BOOL, number=2,) intents = proto.RepeatedField(proto.MESSAGE, number=1, message=Intent,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class CalculateCoverageRequest(proto.Message): @@ -508,8 +466,7 @@ class CoverageType(proto.Enum): PAGE_TRANSITION = 2 TRANSITION_ROUTE_GROUP = 3 - agent = proto.Field(proto.STRING, number=3) - + agent = proto.Field(proto.STRING, number=3,) type_ = proto.Field(proto.ENUM, number=2, enum=CoverageType,) @@ -530,16 +487,13 @@ class CalculateCoverageResponse(proto.Message): Transition route group coverage. """ - agent = proto.Field(proto.STRING, number=5) - + agent = proto.Field(proto.STRING, number=5,) intent_coverage = proto.Field( proto.MESSAGE, number=2, oneof="coverage_type", message="IntentCoverage", ) - transition_coverage = proto.Field( proto.MESSAGE, number=4, oneof="coverage_type", message="TransitionCoverage", ) - route_group_coverage = proto.Field( proto.MESSAGE, number=6, @@ -578,12 +532,9 @@ class TestCaseView(proto.Enum): BASIC = 1 FULL = 2 - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) view = proto.Field(proto.ENUM, number=4, enum=TestCaseView,) @@ -606,8 +557,7 @@ def raw_page(self): return self test_cases = proto.RepeatedField(proto.MESSAGE, number=1, message="TestCase",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class BatchDeleteTestCasesRequest(proto.Message): @@ -623,9 +573,8 @@ class BatchDeleteTestCasesRequest(proto.Message): ``projects//locations/ /agents//testCases/``. """ - parent = proto.Field(proto.STRING, number=1) - - names = proto.RepeatedField(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + names = proto.RepeatedField(proto.STRING, number=3,) class CreateTestCaseRequest(proto.Message): @@ -640,8 +589,7 @@ class CreateTestCaseRequest(proto.Message): Required. The test case to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) test_case = proto.Field(proto.MESSAGE, number=2, message="TestCase",) @@ -662,8 +610,9 @@ class UpdateTestCaseRequest(proto.Message): """ test_case = proto.Field(proto.MESSAGE, number=1, message="TestCase",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class GetTestCaseRequest(proto.Message): @@ -676,7 +625,7 @@ class GetTestCaseRequest(proto.Message): ``projects//locations//agents//testCases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class RunTestCaseRequest(proto.Message): @@ -693,9 +642,8 @@ class RunTestCaseRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) class RunTestCaseResponse(proto.Message): @@ -714,7 +662,7 @@ class RunTestCaseMetadata(proto.Message): r"""Metadata returned for the [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3.TestCases.RunTestCase] long running operation. - """ + """ class BatchRunTestCasesRequest(proto.Message): @@ -733,11 +681,9 @@ class BatchRunTestCasesRequest(proto.Message): ``projects//locations//agents//testCases/``. """ - parent = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) - - test_cases = proto.RepeatedField(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) + test_cases = proto.RepeatedField(proto.STRING, number=3,) class BatchRunTestCasesResponse(proto.Message): @@ -769,7 +715,6 @@ class BatchRunTestCasesMetadata(proto.Message): class TestError(proto.Message): r"""Error info for running a test. - Attributes: test_case (str): The test case resource name. @@ -779,11 +724,9 @@ class TestError(proto.Message): The timestamp when the test was completed. """ - test_case = proto.Field(proto.STRING, number=1) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - - test_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + test_case = proto.Field(proto.STRING, number=1,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) + test_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class ImportTestCasesRequest(proto.Message): @@ -803,11 +746,9 @@ class ImportTestCasesRequest(proto.Message): Uncompressed raw byte content for test cases. """ - parent = proto.Field(proto.STRING, number=1) - - gcs_uri = proto.Field(proto.STRING, number=2, oneof="source") - - content = proto.Field(proto.BYTES, number=3, oneof="source") + parent = proto.Field(proto.STRING, number=1,) + gcs_uri = proto.Field(proto.STRING, number=2, oneof="source",) + content = proto.Field(proto.BYTES, number=3, oneof="source",) class ImportTestCasesResponse(proto.Message): @@ -820,7 +761,7 @@ class ImportTestCasesResponse(proto.Message): ``projects//locations//agents//testCases/``. """ - names = proto.RepeatedField(proto.STRING, number=1) + names = proto.RepeatedField(proto.STRING, number=1,) class ImportTestCasesMetadata(proto.Message): @@ -838,7 +779,6 @@ class ImportTestCasesMetadata(proto.Message): class TestCaseError(proto.Message): r"""Error info for importing a test. - Attributes: test_case (google.cloud.dialogflowcx_v3.types.TestCase): The test case. @@ -847,8 +787,7 @@ class TestCaseError(proto.Message): """ test_case = proto.Field(proto.MESSAGE, number=1, message="TestCase",) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) class ExportTestCasesRequest(proto.Message): @@ -887,13 +826,10 @@ class DataFormat(proto.Enum): BLOB = 1 JSON = 2 - parent = proto.Field(proto.STRING, number=1) - - gcs_uri = proto.Field(proto.STRING, number=2, oneof="destination") - + parent = proto.Field(proto.STRING, number=1,) + gcs_uri = proto.Field(proto.STRING, number=2, oneof="destination",) data_format = proto.Field(proto.ENUM, number=3, enum=DataFormat,) - - filter = proto.Field(proto.STRING, number=4) + filter = proto.Field(proto.STRING, number=4,) class ExportTestCasesResponse(proto.Message): @@ -909,16 +845,15 @@ class ExportTestCasesResponse(proto.Message): Uncompressed raw byte content for test cases. """ - gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination") - - content = proto.Field(proto.BYTES, number=2, oneof="destination") + gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination",) + content = proto.Field(proto.BYTES, number=2, oneof="destination",) class ExportTestCasesMetadata(proto.Message): r"""Metadata returned for the [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3.TestCases.ExportTestCases] long running operation. - """ + """ class ListTestCaseResultsRequest(proto.Message): @@ -965,13 +900,10 @@ class ListTestCaseResultsRequest(proto.Message): 1602540713. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListTestCaseResultsResponse(proto.Message): @@ -994,8 +926,20 @@ def raw_page(self): test_case_results = proto.RepeatedField( proto.MESSAGE, number=1, message="TestCaseResult", ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetTestCaseResultRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3.TestCases.GetTestCaseResult]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + """ - next_page_token = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/transition_route_group.py b/google/cloud/dialogflowcx_v3/types/transition_route_group.py index bf59b515..ed10a1a0 100644 --- a/google/cloud/dialogflowcx_v3/types/transition_route_group.py +++ b/google/cloud/dialogflowcx_v3/types/transition_route_group.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import page -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -57,10 +54,8 @@ class TransitionRouteGroup(proto.Message): [TransitionRouteGroup][google.cloud.dialogflow.cx.v3.TransitionRouteGroup]. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=5, message=page.TransitionRoute, ) @@ -82,11 +77,13 @@ class ListTransitionRouteGroupsRequest(proto.Message): The next_page_token value returned from a previous list request. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3.TransitionRoute] - is language dependent. + The language to list transition route groups for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -95,13 +92,10 @@ class ListTransitionRouteGroupsRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - language_code = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + language_code = proto.Field(proto.STRING, number=4,) class ListTransitionRouteGroupsResponse(proto.Message): @@ -128,8 +122,7 @@ def raw_page(self): transition_route_groups = proto.RepeatedField( proto.MESSAGE, number=1, message="TransitionRouteGroup", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetTransitionRouteGroupRequest(proto.Message): @@ -143,11 +136,13 @@ class GetTransitionRouteGroupRequest(proto.Message): Format: ``projects//locations//agents//flows//transitionRouteGroups/``. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3.TransitionRoute] - is language dependent. + The language to retrieve the transition route group for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -156,9 +151,8 @@ class GetTransitionRouteGroupRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateTransitionRouteGroupRequest(proto.Message): @@ -175,11 +169,13 @@ class CreateTransitionRouteGroupRequest(proto.Message): Required. The transition route group to create. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3.TransitionRoute] - is language dependent. + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -188,13 +184,11 @@ class CreateTransitionRouteGroupRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) transition_route_group = proto.Field( proto.MESSAGE, number=2, message="TransitionRouteGroup", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateTransitionRouteGroupRequest(proto.Message): @@ -208,11 +202,13 @@ class UpdateTransitionRouteGroupRequest(proto.Message): update_mask (google.protobuf.field_mask_pb2.FieldMask): The mask to control which fields get updated. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3.TransitionRoute] - is language dependent. + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -224,10 +220,10 @@ class UpdateTransitionRouteGroupRequest(proto.Message): transition_route_group = proto.Field( proto.MESSAGE, number=1, message="TransitionRouteGroup", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - - language_code = proto.Field(proto.STRING, number=3) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field(proto.STRING, number=3,) class DeleteTransitionRouteGroupRequest(proto.Message): @@ -252,9 +248,8 @@ class DeleteTransitionRouteGroupRequest(proto.Message): transition route group, as well as any reference to it. """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/validation_message.py b/google/cloud/dialogflowcx_v3/types/validation_message.py index 1355c2d9..7da57f7e 100644 --- a/google/cloud/dialogflowcx_v3/types/validation_message.py +++ b/google/cloud/dialogflowcx_v3/types/validation_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class ValidationMessage(proto.Message): r"""Agent/flow validation message. - Attributes: resource_type (google.cloud.dialogflowcx_v3.types.ValidationMessage.ResourceType): The type of the resources where the message @@ -68,21 +65,16 @@ class Severity(proto.Enum): ERROR = 3 resource_type = proto.Field(proto.ENUM, number=1, enum=ResourceType,) - - resources = proto.RepeatedField(proto.STRING, number=2) - + resources = proto.RepeatedField(proto.STRING, number=2,) resource_names = proto.RepeatedField( proto.MESSAGE, number=6, message="ResourceName", ) - severity = proto.Field(proto.ENUM, number=3, enum=Severity,) - - detail = proto.Field(proto.STRING, number=4) + detail = proto.Field(proto.STRING, number=4,) class ResourceName(proto.Message): r"""Resource name and display name. - Attributes: name (str): Name. @@ -90,9 +82,8 @@ class ResourceName(proto.Message): Display name. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/version.py b/google/cloud/dialogflowcx_v3/types/version.py index b5351155..75a2f290 100644 --- a/google/cloud/dialogflowcx_v3/types/version.py +++ b/google/cloud/dialogflowcx_v3/types/version.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import flow -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -49,12 +46,11 @@ class CreateVersionOperationMetadata(proto.Message): ``projects//locations//agents//flows//versions/``. """ - version = proto.Field(proto.STRING, number=1) + version = proto.Field(proto.STRING, number=1,) class Version(proto.Message): r"""Represents a version of a flow. - Attributes: name (str): Format: projects//locations//agents//flows//versions/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateVersionRequest(proto.Message): @@ -177,8 +165,7 @@ class CreateVersionRequest(proto.Message): Required. The version to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) version = proto.Field(proto.MESSAGE, number=2, message="Version",) @@ -196,8 +183,9 @@ class UpdateVersionRequest(proto.Message): """ version = proto.Field(proto.MESSAGE, number=1, message="Version",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteVersionRequest(proto.Message): @@ -212,7 +200,7 @@ class DeleteVersionRequest(proto.Message): ``projects//locations//agents//flows//versions/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class LoadVersionRequest(proto.Message): @@ -223,20 +211,18 @@ class LoadVersionRequest(proto.Message): name (str): Required. The [Version][google.cloud.dialogflow.cx.v3.Version] to be - loaded to draft version. Format: + loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. allow_override_agent_resources (bool): This field is used to prevent accidental overwrite of other - agent resources in the draft version, which can potentially - impact other flow's behavior. If - ``allow_override_agent_resources`` is false, conflicted - agent-level resources will not be overridden (i.e. intents, - entities, webhooks). + agent resources, which can potentially impact other flow's + behavior. If ``allow_override_agent_resources`` is false, + conflicted agent-level resources will not be overridden + (i.e. intents, entities, webhooks). """ - name = proto.Field(proto.STRING, number=1) - - allow_override_agent_resources = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + allow_override_agent_resources = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3/types/webhook.py b/google/cloud/dialogflowcx_v3/types/webhook.py index 870977ee..3dd448de 100644 --- a/google/cloud/dialogflowcx_v3/types/webhook.py +++ b/google/cloud/dialogflowcx_v3/types/webhook.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3.types import response_message -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -62,6 +59,10 @@ 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. + service_directory (google.cloud.dialogflowcx_v3.types.Webhook.ServiceDirectoryConfig): + Configuration for a `Service + Directory `__ + service. timeout (google.protobuf.duration_pb2.Duration): Webhook execution timeout. Execution is considered failed if Dialogflow doesn't receive @@ -74,7 +75,6 @@ class Webhook(proto.Message): class GenericWebService(proto.Message): r"""Represents configuration for a generic web service. - Attributes: uri (str): Required. The webhook URI for receiving POST @@ -88,25 +88,43 @@ class GenericWebService(proto.Message): with webhook requests. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + username = proto.Field(proto.STRING, number=2,) + password = proto.Field(proto.STRING, number=3,) + request_headers = proto.MapField(proto.STRING, proto.STRING, number=4,) - username = proto.Field(proto.STRING, number=2) + class ServiceDirectoryConfig(proto.Message): + r"""Represents configuration for a `Service + Directory `__ service. - password = proto.Field(proto.STRING, number=3) - - request_headers = proto.MapField(proto.STRING, proto.STRING, number=4) - - name = proto.Field(proto.STRING, number=1) + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``Location ID`` of the service directory must be the same as + the location of the agent. + generic_web_service (google.cloud.dialogflowcx_v3.types.Webhook.GenericWebService): + Generic Service configuration of this + webhook. + """ - display_name = proto.Field(proto.STRING, number=2) + service = proto.Field(proto.STRING, number=1,) + generic_web_service = proto.Field( + proto.MESSAGE, number=2, message="Webhook.GenericWebService", + ) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) generic_web_service = proto.Field( proto.MESSAGE, number=4, oneof="webhook", message=GenericWebService, ) - - timeout = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - disabled = proto.Field(proto.BOOL, number=5) + service_directory = proto.Field( + proto.MESSAGE, number=7, oneof="webhook", message=ServiceDirectoryConfig, + ) + timeout = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration,) + disabled = proto.Field(proto.BOOL, number=5,) class ListWebhooksRequest(proto.Message): @@ -125,11 +143,9 @@ class ListWebhooksRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListWebhooksResponse(proto.Message): @@ -151,8 +167,7 @@ def raw_page(self): return self webhooks = proto.RepeatedField(proto.MESSAGE, number=1, message="Webhook",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetWebhookRequest(proto.Message): @@ -165,7 +180,7 @@ class GetWebhookRequest(proto.Message): ``projects//locations//agents//webhooks/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateWebhookRequest(proto.Message): @@ -180,8 +195,7 @@ class CreateWebhookRequest(proto.Message): Required. The webhook to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) webhook = proto.Field(proto.MESSAGE, number=2, message="Webhook",) @@ -199,8 +213,9 @@ class UpdateWebhookRequest(proto.Message): """ webhook = proto.Field(proto.MESSAGE, number=1, message="Webhook",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteWebhookRequest(proto.Message): @@ -226,19 +241,41 @@ class DeleteWebhookRequest(proto.Message): fulfillments that point to this webhook will be removed). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class WebhookRequest(proto.Message): - r"""The request message for a webhook call. + r"""The request message for a webhook call. The request is sent + as a JSON object and the field names will be presented in camel + cases. Attributes: detect_intent_response_id (str): Always present. The unique identifier of the [DetectIntentResponse][google.cloud.dialogflow.cx.v3.DetectIntentResponse] that will be returned to the API caller. + 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. + 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/``. + 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. + 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. + language_code (str): + The language code specified in the [original + request][QueryInput.language_code]. fulfillment_info (google.cloud.dialogflowcx_v3.types.WebhookRequest.FulfillmentInfo): Always present. Information about the fulfillment that triggered this webhook call. @@ -272,11 +309,10 @@ class FulfillmentInfo(proto.Message): which fulfillment is being called. """ - tag = proto.Field(proto.STRING, number=1) + tag = proto.Field(proto.STRING, number=1,) class IntentInfo(proto.Message): r"""Represents intent information communicated to the webhook. - Attributes: last_matched_intent (str): Always present. The unique identifier of the last matched @@ -300,7 +336,6 @@ class IntentInfo(proto.Message): class IntentParameterValue(proto.Message): r"""Represents a value for an intent parameter. - Attributes: original_value (str): Always present. Original text value extracted @@ -310,26 +345,23 @@ class IntentParameterValue(proto.Message): parameter extracted from user utterance. """ - original_value = proto.Field(proto.STRING, number=1) - - resolved_value = proto.Field(proto.MESSAGE, number=2, message=struct.Value,) - - last_matched_intent = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=3) + original_value = proto.Field(proto.STRING, number=1,) + resolved_value = proto.Field( + proto.MESSAGE, number=2, message=struct_pb2.Value, + ) + last_matched_intent = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=3,) parameters = proto.MapField( proto.STRING, proto.MESSAGE, number=2, message="WebhookRequest.IntentInfo.IntentParameterValue", ) - - confidence = proto.Field(proto.FLOAT, number=4) + confidence = proto.Field(proto.FLOAT, number=4,) class SentimentAnalysisResult(proto.Message): r"""Represents the result of sentiment analysis. - Attributes: score (float): Sentiment score between -1.0 (negative @@ -340,26 +372,23 @@ class SentimentAnalysisResult(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) - - detect_intent_response_id = proto.Field(proto.STRING, number=1) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) + detect_intent_response_id = proto.Field(proto.STRING, number=1,) + text = proto.Field(proto.STRING, number=10, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=11, oneof="query",) + transcript = proto.Field(proto.STRING, number=12, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=14, oneof="query",) + language_code = proto.Field(proto.STRING, number=15,) fulfillment_info = proto.Field(proto.MESSAGE, number=6, message=FulfillmentInfo,) - intent_info = proto.Field(proto.MESSAGE, number=3, message=IntentInfo,) - page_info = proto.Field(proto.MESSAGE, number=4, message="PageInfo",) - session_info = proto.Field(proto.MESSAGE, number=5, message="SessionInfo",) - messages = proto.RepeatedField( proto.MESSAGE, number=7, message=response_message.ResponseMessage, ) - - payload = proto.Field(proto.MESSAGE, number=8, message=struct.Struct,) - + payload = proto.Field(proto.MESSAGE, number=8, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=9, message=SentimentAnalysisResult, ) @@ -367,7 +396,6 @@ class SentimentAnalysisResult(proto.Message): class WebhookResponse(proto.Message): r"""The response message for a webhook call. - Attributes: fulfillment_response (google.cloud.dialogflowcx_v3.types.WebhookResponse.FulfillmentResponse): The fulfillment response to send to the user. @@ -395,7 +423,6 @@ class WebhookResponse(proto.Message): class FulfillmentResponse(proto.Message): r"""Represents a fulfillment response to the user. - Attributes: messages (Sequence[google.cloud.dialogflowcx_v3.types.ResponseMessage]): The list of rich message responses to present @@ -413,7 +440,6 @@ class MergeBehavior(proto.Enum): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=response_message.ResponseMessage, ) - merge_behavior = proto.Field( proto.ENUM, number=2, @@ -423,16 +449,11 @@ class MergeBehavior(proto.Enum): fulfillment_response = proto.Field( proto.MESSAGE, number=1, message=FulfillmentResponse, ) - page_info = proto.Field(proto.MESSAGE, number=2, message="PageInfo",) - session_info = proto.Field(proto.MESSAGE, number=3, message="SessionInfo",) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - target_page = proto.Field(proto.STRING, number=5, oneof="transition") - - target_flow = proto.Field(proto.STRING, number=6, oneof="transition") + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + target_page = proto.Field(proto.STRING, number=5, oneof="transition",) + target_flow = proto.Field(proto.STRING, number=6, oneof="transition",) class PageInfo(proto.Message): @@ -457,7 +478,6 @@ class PageInfo(proto.Message): class FormInfo(proto.Message): r"""Represents form information. - Attributes: parameter_info (Sequence[google.cloud.dialogflowcx_v3.types.PageInfo.FormInfo.ParameterInfo]): Optional for both @@ -470,7 +490,6 @@ class FormInfo(proto.Message): class ParameterInfo(proto.Message): r"""Represents parameter information. - Attributes: display_name (str): Always present for @@ -520,26 +539,21 @@ class ParameterState(proto.Enum): INVALID = 2 FILLED = 3 - display_name = proto.Field(proto.STRING, number=1) - - required = proto.Field(proto.BOOL, number=2) - + display_name = proto.Field(proto.STRING, number=1,) + required = proto.Field(proto.BOOL, number=2,) state = proto.Field( proto.ENUM, number=3, enum="PageInfo.FormInfo.ParameterInfo.ParameterState", ) - - value = proto.Field(proto.MESSAGE, number=4, message=struct.Value,) - - just_collected = proto.Field(proto.BOOL, number=5) + value = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Value,) + just_collected = proto.Field(proto.BOOL, number=5,) parameter_info = proto.RepeatedField( proto.MESSAGE, number=2, message="PageInfo.FormInfo.ParameterInfo", ) - current_page = proto.Field(proto.STRING, number=1) - + current_page = proto.Field(proto.STRING, number=1,) form_info = proto.Field(proto.MESSAGE, number=3, message=FormInfo,) @@ -574,10 +588,9 @@ class SessionInfo(proto.Message): The map is keyed by parameters' display names. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) parameters = proto.MapField( - proto.STRING, proto.MESSAGE, number=2, message=struct.Value, + proto.STRING, proto.MESSAGE, number=2, message=struct_pb2.Value, ) diff --git a/google/cloud/dialogflowcx_v3beta1/__init__.py b/google/cloud/dialogflowcx_v3beta1/__init__.py index b85b6810..db4a67fb 100644 --- a/google/cloud/dialogflowcx_v3beta1/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,19 +15,34 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient from .services.experiments import ExperimentsClient +from .services.experiments import ExperimentsAsyncClient from .services.flows import FlowsClient +from .services.flows import FlowsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.pages import PagesClient +from .services.pages import PagesAsyncClient from .services.security_settings_service import SecuritySettingsServiceClient +from .services.security_settings_service import SecuritySettingsServiceAsyncClient from .services.session_entity_types import SessionEntityTypesClient +from .services.session_entity_types import SessionEntityTypesAsyncClient from .services.sessions import SessionsClient +from .services.sessions import SessionsAsyncClient from .services.test_cases import TestCasesClient +from .services.test_cases import TestCasesAsyncClient from .services.transition_route_groups import TransitionRouteGroupsClient +from .services.transition_route_groups import TransitionRouteGroupsAsyncClient from .services.versions import VersionsClient +from .services.versions import VersionsAsyncClient from .services.webhooks import WebhooksClient +from .services.webhooks import WebhooksAsyncClient + from .types.agent import Agent from .types.agent import AgentValidationResult from .types.agent import CreateAgentRequest @@ -43,15 +57,15 @@ from .types.agent import SpeechToTextSettings from .types.agent import UpdateAgentRequest from .types.agent import ValidateAgentRequest -from .types.audio_config import AudioEncoding from .types.audio_config import InputAudioConfig from .types.audio_config import OutputAudioConfig -from .types.audio_config import OutputAudioEncoding -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechWordInfo -from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig from .types.audio_config import VoiceSelectionParams +from .types.audio_config import AudioEncoding +from .types.audio_config import OutputAudioEncoding +from .types.audio_config import SpeechModelVariant +from .types.audio_config import SsmlVoiceGender from .types.entity_type import CreateEntityTypeRequest from .types.entity_type import DeleteEntityTypeRequest from .types.entity_type import EntityType @@ -81,10 +95,14 @@ from .types.experiment import VersionVariants from .types.flow import CreateFlowRequest from .types.flow import DeleteFlowRequest +from .types.flow import ExportFlowRequest +from .types.flow import ExportFlowResponse from .types.flow import Flow from .types.flow import FlowValidationResult from .types.flow import GetFlowRequest from .types.flow import GetFlowValidationResultRequest +from .types.flow import ImportFlowRequest +from .types.flow import ImportFlowResponse from .types.flow import ListFlowsRequest from .types.flow import ListFlowsResponse from .types.flow import NluSettings @@ -96,10 +114,10 @@ from .types.intent import DeleteIntentRequest from .types.intent import GetIntentRequest from .types.intent import Intent -from .types.intent import IntentView from .types.intent import ListIntentsRequest from .types.intent import ListIntentsResponse from .types.intent import UpdateIntentRequest +from .types.intent import IntentView from .types.page import CreatePageRequest from .types.page import DeletePageRequest from .types.page import EventHandler @@ -156,6 +174,7 @@ from .types.test_case import ExportTestCasesRequest from .types.test_case import ExportTestCasesResponse from .types.test_case import GetTestCaseRequest +from .types.test_case import GetTestCaseResultRequest from .types.test_case import ImportTestCasesMetadata from .types.test_case import ImportTestCasesRequest from .types.test_case import ImportTestCasesResponse @@ -172,11 +191,11 @@ from .types.test_case import TestCaseResult from .types.test_case import TestConfig from .types.test_case import TestError -from .types.test_case import TestResult from .types.test_case import TestRunDifference from .types.test_case import TransitionCoverage from .types.test_case import TransitionRouteGroupCoverage from .types.test_case import UpdateTestCaseRequest +from .types.test_case import TestResult from .types.transition_route_group import CreateTransitionRouteGroupRequest from .types.transition_route_group import DeleteTransitionRouteGroupRequest from .types.transition_route_group import GetTransitionRouteGroupRequest @@ -207,8 +226,21 @@ from .types.webhook import WebhookRequest from .types.webhook import WebhookResponse - __all__ = ( + "AgentsAsyncClient", + "EntityTypesAsyncClient", + "EnvironmentsAsyncClient", + "ExperimentsAsyncClient", + "FlowsAsyncClient", + "IntentsAsyncClient", + "PagesAsyncClient", + "SecuritySettingsServiceAsyncClient", + "SessionEntityTypesAsyncClient", + "SessionsAsyncClient", + "TestCasesAsyncClient", + "TransitionRouteGroupsAsyncClient", + "VersionsAsyncClient", + "WebhooksAsyncClient", "Agent", "AgentValidationResult", "AgentsClient", @@ -260,6 +292,8 @@ "ExperimentsClient", "ExportAgentRequest", "ExportAgentResponse", + "ExportFlowRequest", + "ExportFlowResponse", "ExportTestCasesMetadata", "ExportTestCasesRequest", "ExportTestCasesResponse", @@ -282,9 +316,12 @@ "GetSecuritySettingsRequest", "GetSessionEntityTypeRequest", "GetTestCaseRequest", + "GetTestCaseResultRequest", "GetTransitionRouteGroupRequest", "GetVersionRequest", "GetWebhookRequest", + "ImportFlowRequest", + "ImportFlowResponse", "ImportTestCasesMetadata", "ImportTestCasesRequest", "ImportTestCasesResponse", diff --git a/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json new file mode 100644 index 00000000..c8dd46f2 --- /dev/null +++ b/google/cloud/dialogflowcx_v3beta1/gapic_metadata.json @@ -0,0 +1,1095 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflowcx_v3beta1", + "protoPackage": "google.cloud.dialogflow.cx.v3beta1", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetAgentValidationResult": { + "methods": [ + "get_agent_validation_result" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "ValidateAgent": { + "methods": [ + "validate_agent" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EntityTypesAsyncClient", + "rpcs": { + "CreateEntityType": { + "methods": [ + "create_entity_type" + ] + }, + "DeleteEntityType": { + "methods": [ + "delete_entity_type" + ] + }, + "GetEntityType": { + "methods": [ + "get_entity_type" + ] + }, + "ListEntityTypes": { + "methods": [ + "list_entity_types" + ] + }, + "UpdateEntityType": { + "methods": [ + "update_entity_type" + ] + } + } + } + } + }, + "Environments": { + "clients": { + "grpc": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LookupEnvironmentHistory": { + "methods": [ + "lookup_environment_history" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Experiments": { + "clients": { + "grpc": { + "libraryClient": "ExperimentsClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ExperimentsAsyncClient", + "rpcs": { + "CreateExperiment": { + "methods": [ + "create_experiment" + ] + }, + "DeleteExperiment": { + "methods": [ + "delete_experiment" + ] + }, + "GetExperiment": { + "methods": [ + "get_experiment" + ] + }, + "ListExperiments": { + "methods": [ + "list_experiments" + ] + }, + "StartExperiment": { + "methods": [ + "start_experiment" + ] + }, + "StopExperiment": { + "methods": [ + "stop_experiment" + ] + }, + "UpdateExperiment": { + "methods": [ + "update_experiment" + ] + } + } + } + } + }, + "Flows": { + "clients": { + "grpc": { + "libraryClient": "FlowsClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FlowsAsyncClient", + "rpcs": { + "CreateFlow": { + "methods": [ + "create_flow" + ] + }, + "DeleteFlow": { + "methods": [ + "delete_flow" + ] + }, + "ExportFlow": { + "methods": [ + "export_flow" + ] + }, + "GetFlow": { + "methods": [ + "get_flow" + ] + }, + "GetFlowValidationResult": { + "methods": [ + "get_flow_validation_result" + ] + }, + "ImportFlow": { + "methods": [ + "import_flow" + ] + }, + "ListFlows": { + "methods": [ + "list_flows" + ] + }, + "TrainFlow": { + "methods": [ + "train_flow" + ] + }, + "UpdateFlow": { + "methods": [ + "update_flow" + ] + }, + "ValidateFlow": { + "methods": [ + "validate_flow" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "IntentsAsyncClient", + "rpcs": { + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "Pages": { + "clients": { + "grpc": { + "libraryClient": "PagesClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PagesAsyncClient", + "rpcs": { + "CreatePage": { + "methods": [ + "create_page" + ] + }, + "DeletePage": { + "methods": [ + "delete_page" + ] + }, + "GetPage": { + "methods": [ + "get_page" + ] + }, + "ListPages": { + "methods": [ + "list_pages" + ] + }, + "UpdatePage": { + "methods": [ + "update_page" + ] + } + } + } + } + }, + "SecuritySettingsService": { + "clients": { + "grpc": { + "libraryClient": "SecuritySettingsServiceClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SecuritySettingsServiceAsyncClient", + "rpcs": { + "CreateSecuritySettings": { + "methods": [ + "create_security_settings" + ] + }, + "DeleteSecuritySettings": { + "methods": [ + "delete_security_settings" + ] + }, + "GetSecuritySettings": { + "methods": [ + "get_security_settings" + ] + }, + "ListSecuritySettings": { + "methods": [ + "list_security_settings" + ] + }, + "UpdateSecuritySettings": { + "methods": [ + "update_security_settings" + ] + } + } + } + } + }, + "SessionEntityTypes": { + "clients": { + "grpc": { + "libraryClient": "SessionEntityTypesClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionEntityTypesAsyncClient", + "rpcs": { + "CreateSessionEntityType": { + "methods": [ + "create_session_entity_type" + ] + }, + "DeleteSessionEntityType": { + "methods": [ + "delete_session_entity_type" + ] + }, + "GetSessionEntityType": { + "methods": [ + "get_session_entity_type" + ] + }, + "ListSessionEntityTypes": { + "methods": [ + "list_session_entity_types" + ] + }, + "UpdateSessionEntityType": { + "methods": [ + "update_session_entity_type" + ] + } + } + } + } + }, + "Sessions": { + "clients": { + "grpc": { + "libraryClient": "SessionsClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "FulfillIntent": { + "methods": [ + "fulfill_intent" + ] + }, + "MatchIntent": { + "methods": [ + "match_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "TestCases": { + "clients": { + "grpc": { + "libraryClient": "TestCasesClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TestCasesAsyncClient", + "rpcs": { + "BatchDeleteTestCases": { + "methods": [ + "batch_delete_test_cases" + ] + }, + "BatchRunTestCases": { + "methods": [ + "batch_run_test_cases" + ] + }, + "CalculateCoverage": { + "methods": [ + "calculate_coverage" + ] + }, + "CreateTestCase": { + "methods": [ + "create_test_case" + ] + }, + "ExportTestCases": { + "methods": [ + "export_test_cases" + ] + }, + "GetTestCase": { + "methods": [ + "get_test_case" + ] + }, + "GetTestCaseResult": { + "methods": [ + "get_test_case_result" + ] + }, + "ImportTestCases": { + "methods": [ + "import_test_cases" + ] + }, + "ListTestCaseResults": { + "methods": [ + "list_test_case_results" + ] + }, + "ListTestCases": { + "methods": [ + "list_test_cases" + ] + }, + "RunTestCase": { + "methods": [ + "run_test_case" + ] + }, + "UpdateTestCase": { + "methods": [ + "update_test_case" + ] + } + } + } + } + }, + "TransitionRouteGroups": { + "clients": { + "grpc": { + "libraryClient": "TransitionRouteGroupsClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + }, + "grpc-async": { + "libraryClient": "TransitionRouteGroupsAsyncClient", + "rpcs": { + "CreateTransitionRouteGroup": { + "methods": [ + "create_transition_route_group" + ] + }, + "DeleteTransitionRouteGroup": { + "methods": [ + "delete_transition_route_group" + ] + }, + "GetTransitionRouteGroup": { + "methods": [ + "get_transition_route_group" + ] + }, + "ListTransitionRouteGroups": { + "methods": [ + "list_transition_route_groups" + ] + }, + "UpdateTransitionRouteGroup": { + "methods": [ + "update_transition_route_group" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "VersionsAsyncClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "LoadVersion": { + "methods": [ + "load_version" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + }, + "Webhooks": { + "clients": { + "grpc": { + "libraryClient": "WebhooksClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WebhooksAsyncClient", + "rpcs": { + "CreateWebhook": { + "methods": [ + "create_webhook" + ] + }, + "DeleteWebhook": { + "methods": [ + "delete_webhook" + ] + }, + "GetWebhook": { + "methods": [ + "get_webhook" + ] + }, + "ListWebhooks": { + "methods": [ + "list_webhooks" + ] + }, + "UpdateWebhook": { + "methods": [ + "update_webhook" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/dialogflowcx_v3beta1/services/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py index 4bcbd7ac..0501fa94 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AgentsClient from .async_client import AgentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py index 7af9f303..7f0d9740 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,10 +32,9 @@ from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport from .client import AgentsClient @@ -61,6 +58,8 @@ class AgentsAsyncClient: parse_agent_validation_result_path = staticmethod( AgentsClient.parse_agent_validation_result_path ) + environment_path = staticmethod(AgentsClient.environment_path) + parse_environment_path = staticmethod(AgentsClient.parse_environment_path) flow_path = staticmethod(AgentsClient.flow_path) parse_flow_path = staticmethod(AgentsClient.parse_flow_path) flow_validation_result_path = staticmethod(AgentsClient.flow_validation_result_path) @@ -71,29 +70,25 @@ class AgentsAsyncClient: parse_security_settings_path = staticmethod( AgentsClient.parse_security_settings_path ) - common_billing_account_path = staticmethod(AgentsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( AgentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AgentsClient.common_folder_path) parse_common_folder_path = staticmethod(AgentsClient.parse_common_folder_path) - common_organization_path = staticmethod(AgentsClient.common_organization_path) parse_common_organization_path = staticmethod( AgentsClient.parse_common_organization_path ) - common_project_path = staticmethod(AgentsClient.common_project_path) parse_common_project_path = staticmethod(AgentsClient.parse_common_project_path) - common_location_path = staticmethod(AgentsClient.common_location_path) parse_common_location_path = staticmethod(AgentsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -108,7 +103,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -125,7 +120,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AgentsTransport: The transport used by the client instance. @@ -139,12 +134,12 @@ def transport(self) -> AgentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AgentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -176,7 +171,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -207,7 +201,6 @@ async def list_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. @@ -237,7 +230,6 @@ async def list_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -289,7 +281,6 @@ async def get_agent( 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. @@ -328,7 +319,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -380,7 +370,6 @@ async def create_agent( This corresponds to the ``agent`` 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. @@ -419,7 +408,6 @@ async def create_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if agent is not None: @@ -450,7 +438,7 @@ async def update_agent( request: gcdc_agent.UpdateAgentRequest = None, *, agent: gcdc_agent.Agent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -474,7 +462,6 @@ async def update_agent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -513,7 +500,6 @@ async def update_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent if update_mask is not None: @@ -563,7 +549,6 @@ async def delete_agent( 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. @@ -584,7 +569,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -621,7 +605,6 @@ async def export_agent( request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -639,7 +622,6 @@ async def export_agent( """ # Create or coerce a protobuf request object. - request = agent.ExportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -664,7 +646,7 @@ async def export_agent( response, self._client._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -687,7 +669,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -714,7 +695,6 @@ async def restore_agent( """ # Create or coerce a protobuf request object. - request = agent.RestoreAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -738,8 +718,8 @@ async def restore_agent( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -762,7 +742,6 @@ async def validate_agent( request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -776,7 +755,6 @@ async def validate_agent( """ # Create or coerce a protobuf request object. - request = agent.ValidateAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -822,7 +800,6 @@ async def get_agent_validation_result( 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. @@ -849,7 +826,6 @@ async def get_agent_validation_result( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py index 2460aaa4..470a5baf 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,10 +36,9 @@ from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import AgentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AgentsGrpcTransport from .transports.grpc_asyncio import AgentsGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class AgentsClientMeta(type): _transport_registry["grpc_asyncio"] = AgentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AgentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -85,7 +82,8 @@ class AgentsClient(metaclass=AgentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -119,7 +117,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -136,7 +135,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -155,23 +154,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AgentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AgentsTransport: The transport used by the client instance. + AgentsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path, @@ -180,30 +180,48 @@ def parse_agent_path(path: str) -> Dict[str, str]: @staticmethod def agent_validation_result_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent_validation_result string.""" + """Returns a fully-qualified agent_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_validation_result_path(path: str) -> Dict[str, str]: - """Parse a agent_validation_result path into its component segments.""" + """Parses a agent_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/validationResult$", path, ) return m.groupdict() if m else {} + @staticmethod + def environment_path( + project: str, location: str, agent: str, environment: str, + ) -> str: + """Returns a fully-qualified environment string.""" + return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( + project=project, location=location, agent=agent, environment=environment, + ) + + @staticmethod + def parse_environment_path(path: str) -> Dict[str, str]: + """Parses a environment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -214,14 +232,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: def flow_validation_result_path( project: str, location: str, agent: str, flow: str, ) -> str: - """Return a fully-qualified flow_validation_result string.""" + """Returns a fully-qualified flow_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_validation_result_path(path: str) -> Dict[str, str]: - """Parse a flow_validation_result path into its component segments.""" + """Parses a flow_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path, @@ -232,14 +250,14 @@ def parse_flow_validation_result_path(path: str) -> Dict[str, str]: def security_settings_path( project: str, location: str, security_settings: str, ) -> str: - """Return a fully-qualified security_settings string.""" + """Returns a fully-qualified security_settings string.""" return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @staticmethod def parse_security_settings_path(path: str) -> Dict[str, str]: - """Parse a security_settings path into its component segments.""" + """Parses a security_settings path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path, @@ -248,7 +266,7 @@ def parse_security_settings_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -261,7 +279,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -272,7 +290,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -283,7 +301,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -294,7 +312,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -308,12 +326,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, AgentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the agents client. + """Instantiates the agents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -368,9 +386,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -382,12 +401,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -402,8 +423,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -441,7 +462,6 @@ def list_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. @@ -473,10 +493,8 @@ def list_agents( # there are no flattened fields. if not isinstance(request, agent.ListAgentsRequest): request = agent.ListAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -524,7 +542,6 @@ def get_agent( 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. @@ -565,10 +582,8 @@ def get_agent( # there are no flattened fields. if not isinstance(request, agent.GetAgentRequest): request = agent.GetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -616,7 +631,6 @@ def create_agent( This corresponds to the ``agent`` 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. @@ -657,10 +671,8 @@ def create_agent( # there are no flattened fields. if not isinstance(request, gcdc_agent.CreateAgentRequest): request = gcdc_agent.CreateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if agent is not None: @@ -687,7 +699,7 @@ def update_agent( request: gcdc_agent.UpdateAgentRequest = None, *, agent: gcdc_agent.Agent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -711,7 +723,6 @@ def update_agent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -752,10 +763,8 @@ def update_agent( # there are no flattened fields. if not isinstance(request, gcdc_agent.UpdateAgentRequest): request = gcdc_agent.UpdateAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent if update_mask is not None: @@ -801,7 +810,6 @@ def delete_agent( 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. @@ -824,10 +832,8 @@ def delete_agent( # there are no flattened fields. if not isinstance(request, agent.DeleteAgentRequest): request = agent.DeleteAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -860,7 +866,6 @@ def export_agent( request (google.cloud.dialogflowcx_v3beta1.types.ExportAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -878,7 +883,6 @@ def export_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ExportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -904,7 +908,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -927,7 +931,6 @@ def restore_agent( request (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -954,7 +957,6 @@ def restore_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.RestoreAgentRequest. # There's no risk of modifying the input as we've already verified @@ -979,8 +981,8 @@ def restore_agent( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -1003,7 +1005,6 @@ def validate_agent( request (google.cloud.dialogflowcx_v3beta1.types.ValidateAgentRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1017,7 +1018,6 @@ def validate_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ValidateAgentRequest. # There's no risk of modifying the input as we've already verified @@ -1064,7 +1064,6 @@ def get_agent_validation_result( 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. @@ -1093,10 +1092,8 @@ def get_agent_validation_result( # there are no flattened fields. if not isinstance(request, agent.GetAgentValidationResultRequest): request = agent.GetAgentValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py index 2f8efd7d..3919627f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py index dfed9192..ceadcd3a 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py index 5f3804f2..5bd4ea98 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class AgentsTransport(abc.ABC): """Abstract transport class for Agents.""" @@ -50,21 +60,24 @@ class AgentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -152,87 +212,77 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ListAgentsRequest], - typing.Union[ - agent.ListAgentsResponse, typing.Awaitable[agent.ListAgentsResponse] - ], + Union[agent.ListAgentsResponse, Awaitable[agent.ListAgentsResponse]], ]: raise NotImplementedError() @property def get_agent( self, - ) -> typing.Callable[ - [agent.GetAgentRequest], - typing.Union[agent.Agent, typing.Awaitable[agent.Agent]], - ]: + ) -> Callable[[agent.GetAgentRequest], Union[agent.Agent, Awaitable[agent.Agent]]]: raise NotImplementedError() @property def create_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_agent.CreateAgentRequest], - typing.Union[gcdc_agent.Agent, typing.Awaitable[gcdc_agent.Agent]], + Union[gcdc_agent.Agent, Awaitable[gcdc_agent.Agent]], ]: raise NotImplementedError() @property def update_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_agent.UpdateAgentRequest], - typing.Union[gcdc_agent.Agent, typing.Awaitable[gcdc_agent.Agent]], + Union[gcdc_agent.Agent, Awaitable[gcdc_agent.Agent]], ]: raise NotImplementedError() @property def delete_agent( self, - ) -> typing.Callable[ - [agent.DeleteAgentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [agent.DeleteAgentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def export_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ExportAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def restore_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.RestoreAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def validate_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ValidateAgentRequest], - typing.Union[ - agent.AgentValidationResult, typing.Awaitable[agent.AgentValidationResult] - ], + Union[agent.AgentValidationResult, Awaitable[agent.AgentValidationResult]], ]: raise NotImplementedError() @property def get_agent_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetAgentValidationResultRequest], - typing.Union[ - agent.AgentValidationResult, typing.Awaitable[agent.AgentValidationResult] - ], + Union[agent.AgentValidationResult, Awaitable[agent.AgentValidationResult]], ]: 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 3b1228b6..b3de9352 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -372,7 +345,7 @@ def update_agent( return self._stubs["update_agent"] @property - def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: + def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty_pb2.Empty]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -391,14 +364,14 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ExportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a binary file. @@ -417,14 +390,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], operations.Operation]: + ) -> Callable[[agent.RestoreAgentRequest], operations_pb2.Operation]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a binary file. @@ -446,7 +419,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] 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 db904280..bdcd0538 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/agents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AgentsTransport, DEFAULT_CLIENT_INFO from .grpc import AgentsGrpcTransport @@ -58,7 +55,7 @@ class AgentsGrpcAsyncIOTransport(AgentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -380,7 +352,7 @@ def update_agent( @property def delete_agent( self, - ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[agent.DeleteAgentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete agent method over gRPC. Deletes the specified agent. @@ -399,14 +371,14 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @property def export_agent( self, - ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ExportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export agent method over gRPC. Exports the specified agent to a binary file. @@ -425,14 +397,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/ExportAgent", request_serializer=agent.ExportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_agent"] @property def restore_agent( self, - ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.RestoreAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the restore agent method over gRPC. Restores the specified agent from a binary file. @@ -454,7 +426,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Agents/RestoreAgent", request_serializer=agent.RestoreAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["restore_agent"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py index f52849c6..77cd53e9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EntityTypesClient from .async_client import EntityTypesAsyncClient 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 a60e969b..dda5c1e4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -50,27 +47,22 @@ class EntityTypesAsyncClient: entity_type_path = staticmethod(EntityTypesClient.entity_type_path) parse_entity_type_path = staticmethod(EntityTypesClient.parse_entity_type_path) - common_billing_account_path = staticmethod( EntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod(EntityTypesClient.parse_common_folder_path) - common_organization_path = staticmethod(EntityTypesClient.common_organization_path) parse_common_organization_path = staticmethod( EntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(EntityTypesClient.common_project_path) parse_common_project_path = staticmethod( EntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(EntityTypesClient.common_location_path) parse_common_location_path = staticmethod( EntityTypesClient.parse_common_location_path @@ -78,7 +70,8 @@ class EntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -93,7 +86,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -110,7 +103,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EntityTypesTransport: The transport used by the client instance. @@ -124,12 +117,12 @@ def transport(self) -> EntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -161,7 +154,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -193,7 +185,6 @@ async def list_entity_types( 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. @@ -223,7 +214,6 @@ async def list_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -275,7 +265,6 @@ async def get_entity_type( 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. @@ -334,7 +323,6 @@ async def get_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -386,7 +374,6 @@ async def create_entity_type( This corresponds to the ``entity_type`` 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. @@ -445,7 +432,6 @@ async def create_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -476,7 +462,7 @@ async def update_entity_type( request: gcdc_entity_type.UpdateEntityTypeRequest = None, *, entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -499,7 +485,6 @@ async def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -558,7 +543,6 @@ async def update_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if update_mask is not None: @@ -608,7 +592,6 @@ async def delete_entity_type( 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. @@ -629,7 +612,6 @@ async def delete_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py index 2876ad6e..77b0b2bc 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,8 +33,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class EntityTypesClientMeta(type): _transport_registry["grpc_asyncio"] = EntityTypesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class EntityTypesClient(metaclass=EntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,10 +149,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EntityTypesTransport: The transport used by the client instance. + EntityTypesTransport: The transport used by the client + instance. """ return self._transport @@ -161,14 +161,14 @@ def transport(self) -> EntityTypesTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -177,7 +177,7 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -190,7 +190,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -201,7 +201,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -237,12 +237,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the entity types client. + """Instantiates the entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -297,9 +297,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -311,12 +312,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -331,8 +334,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -371,7 +374,6 @@ def list_entity_types( 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. @@ -403,10 +405,8 @@ def list_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.ListEntityTypesRequest): request = entity_type.ListEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -454,7 +454,6 @@ def get_entity_type( 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. @@ -515,10 +514,8 @@ def get_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.GetEntityTypeRequest): request = entity_type.GetEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -566,7 +563,6 @@ def create_entity_type( This corresponds to the ``entity_type`` 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. @@ -627,10 +623,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcdc_entity_type.CreateEntityTypeRequest): request = gcdc_entity_type.CreateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_type is not None: @@ -657,7 +651,7 @@ def update_entity_type( request: gcdc_entity_type.UpdateEntityTypeRequest = None, *, entity_type: gcdc_entity_type.EntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -680,7 +674,6 @@ def update_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -741,10 +734,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcdc_entity_type.UpdateEntityTypeRequest): request = gcdc_entity_type.UpdateEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if entity_type is not None: request.entity_type = entity_type if update_mask is not None: @@ -790,7 +781,6 @@ def delete_entity_type( 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. @@ -813,10 +803,8 @@ def delete_entity_type( # there are no flattened fields. if not isinstance(request, entity_type.DeleteEntityTypeRequest): request = entity_type.DeleteEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py index 266f2f48..e30ed843 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py index 963959d1..07ea82e1 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 70191de4..7776bc6b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -48,21 +58,24 @@ class EntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,11 +191,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.ListEntityTypesRequest], - typing.Union[ + Union[ entity_type.ListEntityTypesResponse, - typing.Awaitable[entity_type.ListEntityTypesResponse], + Awaitable[entity_type.ListEntityTypesResponse], ], ]: raise NotImplementedError() @@ -143,40 +203,36 @@ def list_entity_types( @property def get_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.GetEntityTypeRequest], - typing.Union[entity_type.EntityType, typing.Awaitable[entity_type.EntityType]], + Union[entity_type.EntityType, Awaitable[entity_type.EntityType]], ]: raise NotImplementedError() @property def create_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcdc_entity_type.EntityType, typing.Awaitable[gcdc_entity_type.EntityType] - ], + Union[gcdc_entity_type.EntityType, Awaitable[gcdc_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcdc_entity_type.EntityType, typing.Awaitable[gcdc_entity_type.EntityType] - ], + Union[gcdc_entity_type.EntityType, Awaitable[gcdc_entity_type.EntityType]], ]: raise NotImplementedError() @property def delete_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.DeleteEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py index cfb023ce..a709a61c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -365,7 +338,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty.Empty]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], empty_pb2.Empty]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -384,7 +357,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] 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 7f766a58..c565b0fc 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import entity_type from google.cloud.dialogflowcx_v3beta1.types import entity_type as gcdc_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -56,7 +53,7 @@ class EntityTypesGrpcAsyncIOTransport(EntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -374,7 +346,7 @@ def update_entity_type( @property def delete_entity_type( self, - ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty.Empty]]: + ) -> Callable[[entity_type.DeleteEntityTypeRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete entity type method over gRPC. Deletes the specified entity type. @@ -393,7 +365,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.EntityTypes/DeleteEntityType", request_serializer=entity_type.DeleteEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_entity_type"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py index a67f2316..0c2be948 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import EnvironmentsClient from .async_client import EnvironmentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py index 145158e6..7f9c961c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,10 +31,9 @@ from google.cloud.dialogflowcx_v3beta1.services.environments import pagers from google.cloud.dialogflowcx_v3beta1.types import environment from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport from .client import EnvironmentsClient @@ -56,27 +53,22 @@ class EnvironmentsAsyncClient: parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) version_path = staticmethod(EnvironmentsClient.version_path) parse_version_path = staticmethod(EnvironmentsClient.parse_version_path) - common_billing_account_path = staticmethod( EnvironmentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( EnvironmentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(EnvironmentsClient.common_folder_path) parse_common_folder_path = staticmethod(EnvironmentsClient.parse_common_folder_path) - common_organization_path = staticmethod(EnvironmentsClient.common_organization_path) parse_common_organization_path = staticmethod( EnvironmentsClient.parse_common_organization_path ) - common_project_path = staticmethod(EnvironmentsClient.common_project_path) parse_common_project_path = staticmethod( EnvironmentsClient.parse_common_project_path ) - common_location_path = staticmethod(EnvironmentsClient.common_location_path) parse_common_location_path = staticmethod( EnvironmentsClient.parse_common_location_path @@ -84,7 +76,8 @@ class EnvironmentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -99,7 +92,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -116,7 +109,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: EnvironmentsTransport: The transport used by the client instance. @@ -130,12 +123,12 @@ def transport(self) -> EnvironmentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -167,7 +160,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -200,7 +192,6 @@ async def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -230,7 +221,6 @@ async def list_environments( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -285,7 +275,6 @@ async def get_environment( 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. @@ -325,7 +314,6 @@ async def get_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -383,7 +371,6 @@ async def create_environment( This corresponds to the ``environment`` 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. @@ -421,7 +408,6 @@ async def create_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if environment is not None: @@ -449,7 +435,7 @@ async def create_environment( response, self._client._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -460,7 +446,7 @@ async def update_environment( request: gcdc_environment.UpdateEnvironmentRequest = None, *, environment: gcdc_environment.Environment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -484,7 +470,6 @@ async def update_environment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -522,7 +507,6 @@ async def update_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if environment is not None: request.environment = environment if update_mask is not None: @@ -552,7 +536,7 @@ async def update_environment( response, self._client._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -583,7 +567,6 @@ async def delete_environment( 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. @@ -604,7 +587,6 @@ async def delete_environment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -651,7 +633,6 @@ async def lookup_environment_history( 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. @@ -681,7 +662,6 @@ async def lookup_environment_history( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py index 5ca9988e..a3ec88d7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,10 +35,9 @@ from google.cloud.dialogflowcx_v3beta1.services.environments import pagers from google.cloud.dialogflowcx_v3beta1.types import environment from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EnvironmentsGrpcTransport from .transports.grpc_asyncio import EnvironmentsGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class EnvironmentsClientMeta(type): _transport_registry["grpc_asyncio"] = EnvironmentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[EnvironmentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class EnvironmentsClient(metaclass=EnvironmentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,10 +153,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> EnvironmentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - EnvironmentsTransport: The transport used by the client instance. + EnvironmentsTransport: The transport used by the client + instance. """ return self._transport @@ -165,14 +165,14 @@ def transport(self) -> EnvironmentsTransport: def environment_path( project: str, location: str, agent: str, environment: str, ) -> str: - """Return a fully-qualified environment string.""" + """Returns a fully-qualified environment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @staticmethod def parse_environment_path(path: str) -> Dict[str, str]: - """Parse a environment path into its component segments.""" + """Parses a environment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path, @@ -183,14 +183,14 @@ def parse_environment_path(path: str) -> Dict[str, str]: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -199,7 +199,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -212,7 +212,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -245,7 +245,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -259,12 +259,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, EnvironmentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the environments client. + """Instantiates the environments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -319,9 +319,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -333,12 +334,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -353,8 +356,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -394,7 +397,6 @@ def list_environments( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -426,10 +428,8 @@ def list_environments( # there are no flattened fields. if not isinstance(request, environment.ListEnvironmentsRequest): request = environment.ListEnvironmentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -480,7 +480,6 @@ def get_environment( 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. @@ -522,10 +521,8 @@ def get_environment( # there are no flattened fields. if not isinstance(request, environment.GetEnvironmentRequest): request = environment.GetEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -579,7 +576,6 @@ def create_environment( This corresponds to the ``environment`` 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. @@ -619,10 +615,8 @@ def create_environment( # there are no flattened fields. if not isinstance(request, gcdc_environment.CreateEnvironmentRequest): request = gcdc_environment.CreateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if environment is not None: @@ -646,7 +640,7 @@ def create_environment( response, self._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -657,7 +651,7 @@ def update_environment( request: gcdc_environment.UpdateEnvironmentRequest = None, *, environment: gcdc_environment.Environment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -681,7 +675,6 @@ def update_environment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -721,10 +714,8 @@ def update_environment( # there are no flattened fields. if not isinstance(request, gcdc_environment.UpdateEnvironmentRequest): request = gcdc_environment.UpdateEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if environment is not None: request.environment = environment if update_mask is not None: @@ -750,7 +741,7 @@ def update_environment( response, self._transport.operations_client, gcdc_environment.Environment, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -781,7 +772,6 @@ def delete_environment( 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. @@ -804,10 +794,8 @@ def delete_environment( # there are no flattened fields. if not isinstance(request, environment.DeleteEnvironmentRequest): request = environment.DeleteEnvironmentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -850,7 +838,6 @@ def lookup_environment_history( 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. @@ -882,10 +869,8 @@ def lookup_environment_history( # there are no flattened fields. if not isinstance(request, environment.LookupEnvironmentHistoryRequest): request = environment.LookupEnvironmentHistoryRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py index a2f63ff2..53d80e94 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py index aff44bcd..c72efee4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py index ab03d579..8ddda462 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore 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 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class EnvironmentsTransport(abc.ABC): """Abstract transport class for Environments.""" @@ -50,21 +60,24 @@ class EnvironmentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], ], ]: raise NotImplementedError() @@ -155,49 +215,47 @@ def list_environments( @property def get_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.GetEnvironmentRequest], - typing.Union[ - environment.Environment, typing.Awaitable[environment.Environment] - ], + Union[environment.Environment, Awaitable[environment.Environment]], ]: raise NotImplementedError() @property def create_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_environment.CreateEnvironmentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_environment.UpdateEnvironmentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_environment( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.DeleteEnvironmentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def lookup_environment_history( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.LookupEnvironmentHistoryRequest], - typing.Union[ + Union[ environment.LookupEnvironmentHistoryResponse, - typing.Awaitable[environment.LookupEnvironmentHistoryResponse], + Awaitable[environment.LookupEnvironmentHistoryResponse], ], ]: 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 ab31da64..01aac0ae 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 environment from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -327,7 +300,9 @@ def get_environment( @property def create_environment( self, - ) -> Callable[[gcdc_environment.CreateEnvironmentRequest], operations.Operation]: + ) -> Callable[ + [gcdc_environment.CreateEnvironmentRequest], operations_pb2.Operation + ]: r"""Return a callable for the create environment method over gRPC. Creates an @@ -348,14 +323,16 @@ def create_environment( self._stubs["create_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment", request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_environment"] @property def update_environment( self, - ) -> Callable[[gcdc_environment.UpdateEnvironmentRequest], operations.Operation]: + ) -> Callable[ + [gcdc_environment.UpdateEnvironmentRequest], operations_pb2.Operation + ]: r"""Return a callable for the update environment method over gRPC. Updates the specified @@ -375,14 +352,14 @@ def update_environment( self._stubs["update_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment", request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_environment"] @property def delete_environment( self, - ) -> Callable[[environment.DeleteEnvironmentRequest], empty.Empty]: + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: r"""Return a callable for the delete environment method over gRPC. Deletes the specified @@ -402,7 +379,7 @@ def delete_environment( self._stubs["delete_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/DeleteEnvironment", request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_environment"] 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 44954784..10474950 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/environments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import environment from google.cloud.dialogflowcx_v3beta1.types import environment as gcdc_environment -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -58,7 +55,7 @@ class EnvironmentsGrpcAsyncIOTransport(EnvironmentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -337,7 +309,7 @@ def get_environment( def create_environment( self, ) -> Callable[ - [gcdc_environment.CreateEnvironmentRequest], Awaitable[operations.Operation] + [gcdc_environment.CreateEnvironmentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create environment method over gRPC. @@ -359,7 +331,7 @@ def create_environment( self._stubs["create_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/CreateEnvironment", request_serializer=gcdc_environment.CreateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_environment"] @@ -367,7 +339,7 @@ def create_environment( def update_environment( self, ) -> Callable[ - [gcdc_environment.UpdateEnvironmentRequest], Awaitable[operations.Operation] + [gcdc_environment.UpdateEnvironmentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update environment method over gRPC. @@ -388,14 +360,14 @@ def update_environment( self._stubs["update_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/UpdateEnvironment", request_serializer=gcdc_environment.UpdateEnvironmentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_environment"] @property def delete_environment( self, - ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete environment method over gRPC. Deletes the specified @@ -415,7 +387,7 @@ def delete_environment( self._stubs["delete_environment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Environments/DeleteEnvironment", request_serializer=environment.DeleteEnvironmentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_environment"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py index c9141d08..560b13da 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ExperimentsClient from .async_client import ExperimentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py index c92fd8cd..b7497562 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,19 +20,18 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport from .client import ExperimentsClient @@ -54,27 +51,22 @@ class ExperimentsAsyncClient: parse_experiment_path = staticmethod(ExperimentsClient.parse_experiment_path) version_path = staticmethod(ExperimentsClient.version_path) parse_version_path = staticmethod(ExperimentsClient.parse_version_path) - common_billing_account_path = staticmethod( ExperimentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ExperimentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ExperimentsClient.common_folder_path) parse_common_folder_path = staticmethod(ExperimentsClient.parse_common_folder_path) - common_organization_path = staticmethod(ExperimentsClient.common_organization_path) parse_common_organization_path = staticmethod( ExperimentsClient.parse_common_organization_path ) - common_project_path = staticmethod(ExperimentsClient.common_project_path) parse_common_project_path = staticmethod( ExperimentsClient.parse_common_project_path ) - common_location_path = staticmethod(ExperimentsClient.common_location_path) parse_common_location_path = staticmethod( ExperimentsClient.parse_common_location_path @@ -82,7 +74,8 @@ class ExperimentsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -97,7 +90,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -114,7 +107,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ExperimentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ExperimentsTransport: The transport used by the client instance. @@ -128,12 +121,12 @@ def transport(self) -> ExperimentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ExperimentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the experiments client. + """Instantiates the experiments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -165,7 +158,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ExperimentsClient( credentials=credentials, transport=transport, @@ -198,7 +190,6 @@ async def list_experiments( 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. @@ -228,7 +219,6 @@ async def list_experiments( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -283,7 +273,6 @@ async def get_experiment( 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. @@ -310,7 +299,6 @@ async def get_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -369,7 +357,6 @@ async def create_experiment( This corresponds to the ``experiment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -396,7 +383,6 @@ async def create_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if experiment is not None: @@ -427,7 +413,7 @@ async def update_experiment( request: gcdc_experiment.UpdateExperimentRequest = None, *, experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -451,7 +437,6 @@ async def update_experiment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -478,7 +463,6 @@ async def update_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if experiment is not None: request.experiment = experiment if update_mask is not None: @@ -531,7 +515,6 @@ async def delete_experiment( 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. @@ -552,7 +535,6 @@ async def delete_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -601,7 +583,6 @@ async def start_experiment( 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. @@ -628,7 +609,6 @@ async def start_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -678,7 +658,6 @@ async def stop_experiment( 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. @@ -705,7 +684,6 @@ async def stop_experiment( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py index 84570049..c7aa6534 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,10 +33,9 @@ from google.cloud.dialogflowcx_v3beta1.services.experiments import pagers from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ExperimentsGrpcTransport from .transports.grpc_asyncio import ExperimentsGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class ExperimentsClientMeta(type): _transport_registry["grpc_asyncio"] = ExperimentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ExperimentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -82,7 +79,8 @@ class ExperimentsClient(metaclass=ExperimentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -116,7 +114,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -133,7 +132,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -152,10 +151,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ExperimentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ExperimentsTransport: The transport used by the client instance. + ExperimentsTransport: The transport used by the client + instance. """ return self._transport @@ -163,7 +163,7 @@ def transport(self) -> ExperimentsTransport: def experiment_path( project: str, location: str, agent: str, environment: str, experiment: str, ) -> str: - """Return a fully-qualified experiment string.""" + """Returns a fully-qualified experiment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( project=project, location=location, @@ -174,7 +174,7 @@ def experiment_path( @staticmethod def parse_experiment_path(path: str) -> Dict[str, str]: - """Parse a experiment path into its component segments.""" + """Parses a experiment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)/experiments/(?P.+?)$", path, @@ -185,14 +185,14 @@ def parse_experiment_path(path: str) -> Dict[str, str]: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -201,7 +201,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -214,7 +214,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -225,7 +225,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -236,7 +236,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -247,7 +247,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -261,12 +261,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ExperimentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the experiments client. + """Instantiates the experiments client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -321,9 +321,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -335,12 +336,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -355,8 +358,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -396,7 +399,6 @@ def list_experiments( 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. @@ -428,10 +430,8 @@ def list_experiments( # there are no flattened fields. if not isinstance(request, experiment.ListExperimentsRequest): request = experiment.ListExperimentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -482,7 +482,6 @@ def get_experiment( 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. @@ -511,10 +510,8 @@ def get_experiment( # there are no flattened fields. if not isinstance(request, experiment.GetExperimentRequest): request = experiment.GetExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -569,7 +566,6 @@ def create_experiment( This corresponds to the ``experiment`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -598,10 +594,8 @@ def create_experiment( # there are no flattened fields. if not isinstance(request, gcdc_experiment.CreateExperimentRequest): request = gcdc_experiment.CreateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if experiment is not None: @@ -628,7 +622,7 @@ def update_experiment( request: gcdc_experiment.UpdateExperimentRequest = None, *, experiment: gcdc_experiment.Experiment = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -652,7 +646,6 @@ def update_experiment( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -681,10 +674,8 @@ def update_experiment( # there are no flattened fields. if not isinstance(request, gcdc_experiment.UpdateExperimentRequest): request = gcdc_experiment.UpdateExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if experiment is not None: request.experiment = experiment if update_mask is not None: @@ -733,7 +724,6 @@ def delete_experiment( 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. @@ -756,10 +746,8 @@ def delete_experiment( # there are no flattened fields. if not isinstance(request, experiment.DeleteExperimentRequest): request = experiment.DeleteExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -804,7 +792,6 @@ def start_experiment( 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. @@ -833,10 +820,8 @@ def start_experiment( # there are no flattened fields. if not isinstance(request, experiment.StartExperimentRequest): request = experiment.StartExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -882,7 +867,6 @@ def stop_experiment( 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. @@ -911,10 +895,8 @@ def stop_experiment( # there are no flattened fields. if not isinstance(request, experiment.StopExperimentRequest): request = experiment.StopExperimentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py index 99ae14ea..01c3a204 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py index d1972e23..3be44737 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py index 6f98bde7..de090ca9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class ExperimentsTransport(abc.ABC): """Abstract transport class for Experiments.""" @@ -48,21 +58,24 @@ class ExperimentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -137,11 +197,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_experiments( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.ListExperimentsRequest], - typing.Union[ + Union[ experiment.ListExperimentsResponse, - typing.Awaitable[experiment.ListExperimentsResponse], + Awaitable[experiment.ListExperimentsResponse], ], ]: raise NotImplementedError() @@ -149,58 +209,54 @@ def list_experiments( @property def get_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.GetExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() @property def create_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_experiment.CreateExperimentRequest], - typing.Union[ - gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] - ], + Union[gcdc_experiment.Experiment, Awaitable[gcdc_experiment.Experiment]], ]: raise NotImplementedError() @property def update_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_experiment.UpdateExperimentRequest], - typing.Union[ - gcdc_experiment.Experiment, typing.Awaitable[gcdc_experiment.Experiment] - ], + Union[gcdc_experiment.Experiment, Awaitable[gcdc_experiment.Experiment]], ]: raise NotImplementedError() @property def delete_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.DeleteExperimentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def start_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.StartExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() @property def stop_experiment( self, - ) -> typing.Callable[ + ) -> Callable[ [experiment.StopExperimentRequest], - typing.Union[experiment.Experiment, typing.Awaitable[experiment.Experiment]], + Union[experiment.Experiment, Awaitable[experiment.Experiment]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py index 0a6cc4d2..688fc771 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -370,7 +343,7 @@ def update_experiment( @property def delete_experiment( self, - ) -> Callable[[experiment.DeleteExperimentRequest], empty.Empty]: + ) -> Callable[[experiment.DeleteExperimentRequest], empty_pb2.Empty]: r"""Return a callable for the delete experiment method over gRPC. Deletes the specified @@ -390,7 +363,7 @@ def delete_experiment( self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment", request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_experiment"] 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 afe0a6e2..d56b58cd 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/experiments/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import experiment from google.cloud.dialogflowcx_v3beta1.types import experiment as gcdc_experiment -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ExperimentsTransport, DEFAULT_CLIENT_INFO from .grpc import ExperimentsGrpcTransport @@ -56,7 +53,7 @@ class ExperimentsGrpcAsyncIOTransport(ExperimentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -375,7 +347,7 @@ def update_experiment( @property def delete_experiment( self, - ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[experiment.DeleteExperimentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete experiment method over gRPC. Deletes the specified @@ -395,7 +367,7 @@ def delete_experiment( self._stubs["delete_experiment"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Experiments/DeleteExperiment", request_serializer=experiment.DeleteExperimentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_experiment"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py index edf52773..03ec82a2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import FlowsClient from .async_client import FlowsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py index 4c733bfa..53b414fb 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -35,11 +33,10 @@ from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport from .client import FlowsClient @@ -65,31 +62,31 @@ class FlowsAsyncClient: parse_intent_path = staticmethod(FlowsClient.parse_intent_path) page_path = staticmethod(FlowsClient.page_path) parse_page_path = staticmethod(FlowsClient.parse_page_path) + transition_route_group_path = staticmethod(FlowsClient.transition_route_group_path) + parse_transition_route_group_path = staticmethod( + FlowsClient.parse_transition_route_group_path + ) webhook_path = staticmethod(FlowsClient.webhook_path) parse_webhook_path = staticmethod(FlowsClient.parse_webhook_path) - common_billing_account_path = staticmethod(FlowsClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( FlowsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(FlowsClient.common_folder_path) parse_common_folder_path = staticmethod(FlowsClient.parse_common_folder_path) - common_organization_path = staticmethod(FlowsClient.common_organization_path) parse_common_organization_path = staticmethod( FlowsClient.parse_common_organization_path ) - common_project_path = staticmethod(FlowsClient.common_project_path) parse_common_project_path = staticmethod(FlowsClient.parse_common_project_path) - common_location_path = staticmethod(FlowsClient.common_location_path) parse_common_location_path = staticmethod(FlowsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +101,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +118,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FlowsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: FlowsTransport: The transport used by the client instance. @@ -135,12 +132,12 @@ def transport(self) -> FlowsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, FlowsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the flows client. + """Instantiates the flows client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -172,7 +169,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = FlowsClient( credentials=credentials, transport=transport, @@ -208,7 +204,6 @@ async def create_flow( This corresponds to the ``flow`` 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. @@ -256,7 +251,6 @@ async def create_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if flow is not None: @@ -304,7 +298,6 @@ async def delete_flow( 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. @@ -325,7 +318,6 @@ async def delete_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -370,7 +362,6 @@ async def list_flows( 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. @@ -400,7 +391,6 @@ async def list_flows( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -452,7 +442,6 @@ async def get_flow( 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. @@ -500,7 +489,6 @@ async def get_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -529,7 +517,7 @@ async def update_flow( request: gcdc_flow.UpdateFlowRequest = None, *, flow: gcdc_flow.Flow = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -553,7 +541,6 @@ async def update_flow( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -601,7 +588,6 @@ async def update_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if flow is not None: request.flow = flow if update_mask is not None: @@ -652,7 +638,6 @@ async def train_flow( 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. @@ -692,7 +677,6 @@ async def train_flow( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -717,8 +701,8 @@ async def train_flow( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -741,7 +725,6 @@ async def validate_flow( request (:class:`google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -755,7 +738,6 @@ async def validate_flow( """ # Create or coerce a protobuf request object. - request = flow.ValidateFlowRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -801,7 +783,6 @@ async def get_flow_validation_result( 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. @@ -828,7 +809,6 @@ async def get_flow_validation_result( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -852,6 +832,131 @@ async def get_flow_validation_result( # Done; return the response. return response + async def import_flow( + self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest`): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + async def export_flow( + self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest`): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_flow, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py index cc0db606..0f081120 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -39,11 +37,10 @@ from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import FlowsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import FlowsGrpcTransport from .transports.grpc_asyncio import FlowsGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class FlowsClientMeta(type): _transport_registry["grpc_asyncio"] = FlowsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[FlowsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class FlowsClient(metaclass=FlowsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,23 +156,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> FlowsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - FlowsTransport: The transport used by the client instance. + FlowsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -184,14 +184,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: def flow_validation_result_path( project: str, location: str, agent: str, flow: str, ) -> str: - """Return a fully-qualified flow_validation_result string.""" + """Returns a fully-qualified flow_validation_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_validation_result_path(path: str) -> Dict[str, str]: - """Parse a flow_validation_result path into its component segments.""" + """Parses a flow_validation_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/validationResult$", path, @@ -200,14 +200,14 @@ def parse_flow_validation_result_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -218,30 +218,52 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, ) return m.groupdict() if m else {} + @staticmethod + def transition_route_group_path( + project: str, location: str, agent: str, flow: str, transition_route_group: str, + ) -> str: + """Returns a fully-qualified transition_route_group string.""" + return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( + project=project, + location=location, + agent=agent, + flow=flow, + transition_route_group=transition_route_group, + ) + + @staticmethod + def parse_transition_route_group_path(path: str) -> Dict[str, str]: + """Parses a transition_route_group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -250,7 +272,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -263,7 +285,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -274,7 +296,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -285,7 +307,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -296,7 +318,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -310,12 +332,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, FlowsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the flows client. + """Instantiates the flows client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -370,9 +392,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -384,12 +407,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -404,8 +429,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -448,7 +473,6 @@ def create_flow( This corresponds to the ``flow`` 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. @@ -498,10 +522,8 @@ def create_flow( # there are no flattened fields. if not isinstance(request, gcdc_flow.CreateFlowRequest): request = gcdc_flow.CreateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if flow is not None: @@ -545,7 +567,6 @@ def delete_flow( 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. @@ -568,10 +589,8 @@ def delete_flow( # there are no flattened fields. if not isinstance(request, flow.DeleteFlowRequest): request = flow.DeleteFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -612,7 +631,6 @@ def list_flows( 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. @@ -644,10 +662,8 @@ def list_flows( # there are no flattened fields. if not isinstance(request, flow.ListFlowsRequest): request = flow.ListFlowsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -695,7 +711,6 @@ def get_flow( 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. @@ -745,10 +760,8 @@ def get_flow( # there are no flattened fields. if not isinstance(request, flow.GetFlowRequest): request = flow.GetFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -773,7 +786,7 @@ def update_flow( request: gcdc_flow.UpdateFlowRequest = None, *, flow: gcdc_flow.Flow = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -797,7 +810,6 @@ def update_flow( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -847,10 +859,8 @@ def update_flow( # there are no flattened fields. if not isinstance(request, gcdc_flow.UpdateFlowRequest): request = gcdc_flow.UpdateFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if flow is not None: request.flow = flow if update_mask is not None: @@ -897,7 +907,6 @@ def train_flow( 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. @@ -939,10 +948,8 @@ def train_flow( # there are no flattened fields. if not isinstance(request, flow.TrainFlowRequest): request = flow.TrainFlowRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -963,8 +970,8 @@ def train_flow( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -987,7 +994,6 @@ def validate_flow( request (google.cloud.dialogflowcx_v3beta1.types.ValidateFlowRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1001,7 +1007,6 @@ def validate_flow( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a flow.ValidateFlowRequest. # There's no risk of modifying the input as we've already verified @@ -1048,7 +1053,6 @@ def get_flow_validation_result( 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. @@ -1077,10 +1081,8 @@ def get_flow_validation_result( # there are no flattened fields. if not isinstance(request, flow.GetFlowValidationResultRequest): request = flow.GetFlowValidationResultRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1102,6 +1104,133 @@ def get_flow_validation_result( # Done; return the response. return response + def import_flow( + self, + request: flow.ImportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Imports the specified flow to the specified agent + from a binary file. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ImportFlowResponse` + The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ImportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ImportFlowRequest): + request = flow.ImportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_flow] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ImportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + + def export_flow( + self, + request: flow.ExportFlowRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.ExportFlowRequest): + 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, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.dialogflowcx_v3beta1.types.ExportFlowResponse` + The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a flow.ExportFlowRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, flow.ExportFlowRequest): + request = flow.ExportFlowRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_flow] + + # 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,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + flow.ExportFlowResponse, + metadata_type=struct_pb2.Struct, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py index 84711637..7d4006f7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py index 3789db2a..f2970e47 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py index e1b65780..eda69e57 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import flow from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class FlowsTransport(abc.ABC): """Abstract transport class for Flows.""" @@ -50,21 +60,24 @@ class FlowsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -139,6 +199,12 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.import_flow: gapic_v1.method.wrap_method( + self.import_flow, default_timeout=None, client_info=client_info, + ), + self.export_flow: gapic_v1.method.wrap_method( + self.export_flow, default_timeout=None, client_info=client_info, + ), } @property @@ -149,75 +215,84 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_flow( self, - ) -> typing.Callable[ - [gcdc_flow.CreateFlowRequest], - typing.Union[gcdc_flow.Flow, typing.Awaitable[gcdc_flow.Flow]], + ) -> Callable[ + [gcdc_flow.CreateFlowRequest], Union[gcdc_flow.Flow, Awaitable[gcdc_flow.Flow]] ]: raise NotImplementedError() @property def delete_flow( self, - ) -> typing.Callable[ - [flow.DeleteFlowRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [flow.DeleteFlowRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() @property def list_flows( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.ListFlowsRequest], - typing.Union[flow.ListFlowsResponse, typing.Awaitable[flow.ListFlowsResponse]], + Union[flow.ListFlowsResponse, Awaitable[flow.ListFlowsResponse]], ]: raise NotImplementedError() @property def get_flow( self, - ) -> typing.Callable[ - [flow.GetFlowRequest], typing.Union[flow.Flow, typing.Awaitable[flow.Flow]] - ]: + ) -> Callable[[flow.GetFlowRequest], Union[flow.Flow, Awaitable[flow.Flow]]]: raise NotImplementedError() @property def update_flow( self, - ) -> typing.Callable[ - [gcdc_flow.UpdateFlowRequest], - typing.Union[gcdc_flow.Flow, typing.Awaitable[gcdc_flow.Flow]], + ) -> Callable[ + [gcdc_flow.UpdateFlowRequest], Union[gcdc_flow.Flow, Awaitable[gcdc_flow.Flow]] ]: raise NotImplementedError() @property def train_flow( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.TrainFlowRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def validate_flow( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.ValidateFlowRequest], - typing.Union[ - flow.FlowValidationResult, typing.Awaitable[flow.FlowValidationResult] - ], + Union[flow.FlowValidationResult, Awaitable[flow.FlowValidationResult]], ]: raise NotImplementedError() @property def get_flow_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [flow.GetFlowValidationResultRequest], - typing.Union[ - flow.FlowValidationResult, typing.Awaitable[flow.FlowValidationResult] - ], + Union[flow.FlowValidationResult, Awaitable[flow.FlowValidationResult]], + ]: + raise NotImplementedError() + + @property + def import_flow( + self, + ) -> Callable[ + [flow.ImportFlowRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def export_flow( + self, + ) -> Callable[ + [flow.ExportFlowRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: 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 cd3a4740..f802da9b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 flow from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import FlowsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -293,7 +266,7 @@ def create_flow(self) -> Callable[[gcdc_flow.CreateFlowRequest], gcdc_flow.Flow] return self._stubs["create_flow"] @property - def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty.Empty]: + def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty_pb2.Empty]: r"""Return a callable for the delete flow method over gRPC. Deletes a specified flow. @@ -312,7 +285,7 @@ def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], empty.Empty]: self._stubs["delete_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow", request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_flow"] @@ -389,7 +362,7 @@ def update_flow(self) -> Callable[[gcdc_flow.UpdateFlowRequest], gcdc_flow.Flow] return self._stubs["update_flow"] @property - def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations.Operation]: + def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations_pb2.Operation]: r"""Return a callable for the train flow method over gRPC. Trains the specified flow. Note that only the flow in @@ -409,7 +382,7 @@ def train_flow(self) -> Callable[[flow.TrainFlowRequest], operations.Operation]: self._stubs["train_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow", request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_flow"] @@ -469,5 +442,60 @@ def get_flow_validation_result( ) return self._stubs["get_flow_validation_result"] + @property + def import_flow( + self, + ) -> Callable[[flow.ImportFlowRequest], operations_pb2.Operation]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_flow" not in self._stubs: + self._stubs["import_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow", + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_flow"] + + @property + def export_flow( + self, + ) -> Callable[[flow.ExportFlowRequest], operations_pb2.Operation]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_flow" not in self._stubs: + self._stubs["export_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow", + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_flow"] + __all__ = ("FlowsGrpcTransport",) 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 96562f69..6c2f560e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/flows/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import flow from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import FlowsTransport, DEFAULT_CLIENT_INFO from .grpc import FlowsGrpcTransport @@ -58,7 +55,7 @@ class FlowsGrpcAsyncIOTransport(FlowsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -301,7 +273,9 @@ def create_flow( return self._stubs["create_flow"] @property - def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty.Empty]]: + def delete_flow( + self, + ) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete flow method over gRPC. Deletes a specified flow. @@ -320,7 +294,7 @@ def delete_flow(self) -> Callable[[flow.DeleteFlowRequest], Awaitable[empty.Empt self._stubs["delete_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Flows/DeleteFlow", request_serializer=flow.DeleteFlowRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_flow"] @@ -403,7 +377,7 @@ def update_flow( @property def train_flow( self, - ) -> Callable[[flow.TrainFlowRequest], Awaitable[operations.Operation]]: + ) -> Callable[[flow.TrainFlowRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train flow method over gRPC. Trains the specified flow. Note that only the flow in @@ -423,7 +397,7 @@ def train_flow( self._stubs["train_flow"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Flows/TrainFlow", request_serializer=flow.TrainFlowRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_flow"] @@ -485,5 +459,60 @@ def get_flow_validation_result( ) return self._stubs["get_flow_validation_result"] + @property + def import_flow( + self, + ) -> Callable[[flow.ImportFlowRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import flow method over gRPC. + + Imports the specified flow to the specified agent + from a binary file. + + Returns: + Callable[[~.ImportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_flow" not in self._stubs: + self._stubs["import_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Flows/ImportFlow", + request_serializer=flow.ImportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_flow"] + + @property + def export_flow( + self, + ) -> Callable[[flow.ExportFlowRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export flow method over gRPC. + + Exports the specified flow to a binary file. + Note that resources (e.g. intents, entities, webhooks) + that the flow references will also be exported. + + Returns: + Callable[[~.ExportFlowRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_flow" not in self._stubs: + self._stubs["export_flow"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.Flows/ExportFlow", + request_serializer=flow.ExportFlowRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_flow"] + __all__ = ("FlowsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py index 8719a9b6..5a2c263c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import IntentsClient from .async_client import IntentsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py index dc675ff8..9381483d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.intents import pagers from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -52,31 +49,27 @@ class IntentsAsyncClient: parse_entity_type_path = staticmethod(IntentsClient.parse_entity_type_path) intent_path = staticmethod(IntentsClient.intent_path) parse_intent_path = staticmethod(IntentsClient.parse_intent_path) - common_billing_account_path = staticmethod( IntentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( IntentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(IntentsClient.common_folder_path) parse_common_folder_path = staticmethod(IntentsClient.parse_common_folder_path) - common_organization_path = staticmethod(IntentsClient.common_organization_path) parse_common_organization_path = staticmethod( IntentsClient.parse_common_organization_path ) - common_project_path = staticmethod(IntentsClient.common_project_path) parse_common_project_path = staticmethod(IntentsClient.parse_common_project_path) - common_location_path = staticmethod(IntentsClient.common_location_path) parse_common_location_path = staticmethod(IntentsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -91,7 +84,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -108,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: IntentsTransport: The transport used by the client instance. @@ -122,12 +115,12 @@ def transport(self) -> IntentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, IntentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -159,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -190,7 +182,6 @@ async def list_intents( 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. @@ -220,7 +211,6 @@ async def list_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -272,7 +262,6 @@ async def get_intent( 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. @@ -304,7 +293,6 @@ async def get_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -356,7 +344,6 @@ async def create_intent( This corresponds to the ``intent`` 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. @@ -388,7 +375,6 @@ async def create_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -419,7 +405,7 @@ async def update_intent( request: gcdc_intent.UpdateIntentRequest = None, *, intent: gcdc_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -443,7 +429,6 @@ async def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -475,7 +460,6 @@ async def update_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -525,7 +509,6 @@ async def delete_intent( 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. @@ -546,7 +529,6 @@ async def delete_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/client.py b/google/cloud/dialogflowcx_v3beta1/services/intents/client.py index 1418f739..1ca249f7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,8 +33,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class IntentsClientMeta(type): _transport_registry["grpc_asyncio"] = IntentsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[IntentsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class IntentsClient(metaclass=IntentsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,10 +149,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> IntentsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - IntentsTransport: The transport used by the client instance. + IntentsTransport: The transport used by the client + instance. """ return self._transport @@ -161,14 +161,14 @@ def transport(self) -> IntentsTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -177,14 +177,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -193,7 +193,7 @@ def parse_intent_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -206,7 +206,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -217,7 +217,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -228,7 +228,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -239,7 +239,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -253,12 +253,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, IntentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the intents client. + """Instantiates the intents client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -313,9 +313,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -327,12 +328,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -347,8 +350,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -386,7 +389,6 @@ def list_intents( 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. @@ -418,10 +420,8 @@ def list_intents( # there are no flattened fields. if not isinstance(request, intent.ListIntentsRequest): request = intent.ListIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -469,7 +469,6 @@ def get_intent( 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. @@ -503,10 +502,8 @@ def get_intent( # there are no flattened fields. if not isinstance(request, intent.GetIntentRequest): request = intent.GetIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -554,7 +551,6 @@ def create_intent( This corresponds to the ``intent`` 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. @@ -588,10 +584,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcdc_intent.CreateIntentRequest): request = gcdc_intent.CreateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent is not None: @@ -618,7 +612,7 @@ def update_intent( request: gcdc_intent.UpdateIntentRequest = None, *, intent: gcdc_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -642,7 +636,6 @@ def update_intent( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -676,10 +669,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcdc_intent.UpdateIntentRequest): request = gcdc_intent.UpdateIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if intent is not None: request.intent = intent if update_mask is not None: @@ -725,7 +716,6 @@ def delete_intent( 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. @@ -748,10 +738,8 @@ def delete_intent( # there are no flattened fields. if not isinstance(request, intent.DeleteIntentRequest): request = intent.DeleteIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py index f3f8d5e0..15bc1a62 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py index 41fde33b..974a5810 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py index 20c97c36..901ef629 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -48,21 +58,24 @@ class IntentsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,47 +191,43 @@ def _prep_wrapped_messages(self, client_info): @property def list_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.ListIntentsRequest], - typing.Union[ - intent.ListIntentsResponse, typing.Awaitable[intent.ListIntentsResponse] - ], + Union[intent.ListIntentsResponse, Awaitable[intent.ListIntentsResponse]], ]: raise NotImplementedError() @property def get_intent( self, - ) -> typing.Callable[ - [intent.GetIntentRequest], - typing.Union[intent.Intent, typing.Awaitable[intent.Intent]], + ) -> Callable[ + [intent.GetIntentRequest], Union[intent.Intent, Awaitable[intent.Intent]] ]: raise NotImplementedError() @property def create_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_intent.CreateIntentRequest], - typing.Union[gcdc_intent.Intent, typing.Awaitable[gcdc_intent.Intent]], + Union[gcdc_intent.Intent, Awaitable[gcdc_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_intent.UpdateIntentRequest], - typing.Union[gcdc_intent.Intent, typing.Awaitable[gcdc_intent.Intent]], + Union[gcdc_intent.Intent, Awaitable[gcdc_intent.Intent]], ]: raise NotImplementedError() @property def delete_intent( self, - ) -> typing.Callable[ - [intent.DeleteIntentRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [intent.DeleteIntentRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py index 3cf59920..e2da4f31 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +328,7 @@ def update_intent( return self._stubs["update_intent"] @property - def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: + def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty_pb2.Empty]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent. @@ -374,7 +347,7 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] 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 2a44ac56..f2057bf1 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/intents/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import intent from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -56,7 +53,7 @@ class IntentsGrpcAsyncIOTransport(IntentsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -363,7 +335,7 @@ def update_intent( @property def delete_intent( self, - ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty.Empty]]: + ) -> Callable[[intent.DeleteIntentRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete intent method over gRPC. Deletes the specified intent. @@ -382,7 +354,7 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py index 4fff3f52..c5a52656 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import PagesClient from .async_client import PagesAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py index 1d99a61b..d36d4121 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.pages import pagers 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport from .client import PagesClient @@ -63,29 +60,25 @@ class PagesAsyncClient: ) webhook_path = staticmethod(PagesClient.webhook_path) parse_webhook_path = staticmethod(PagesClient.parse_webhook_path) - common_billing_account_path = staticmethod(PagesClient.common_billing_account_path) parse_common_billing_account_path = staticmethod( PagesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(PagesClient.common_folder_path) parse_common_folder_path = staticmethod(PagesClient.parse_common_folder_path) - common_organization_path = staticmethod(PagesClient.common_organization_path) parse_common_organization_path = staticmethod( PagesClient.parse_common_organization_path ) - common_project_path = staticmethod(PagesClient.common_project_path) parse_common_project_path = staticmethod(PagesClient.parse_common_project_path) - common_location_path = staticmethod(PagesClient.common_location_path) parse_common_location_path = staticmethod(PagesClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -100,7 +93,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -117,7 +110,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PagesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: PagesTransport: The transport used by the client instance. @@ -131,12 +124,12 @@ def transport(self) -> PagesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, PagesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the pages client. + """Instantiates the pages client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -168,7 +161,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = PagesClient( credentials=credentials, transport=transport, @@ -198,7 +190,6 @@ async def list_pages( 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. @@ -228,7 +219,6 @@ async def list_pages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -280,7 +270,6 @@ async def get_page( 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. @@ -327,7 +316,6 @@ async def get_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -379,7 +367,6 @@ async def create_page( This corresponds to the ``page`` 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. @@ -426,7 +413,6 @@ async def create_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if page is not None: @@ -457,7 +443,7 @@ async def update_page( request: gcdc_page.UpdatePageRequest = None, *, page: gcdc_page.Page = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -481,7 +467,6 @@ async def update_page( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -528,7 +513,6 @@ async def update_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if page is not None: request.page = page if update_mask is not None: @@ -578,7 +562,6 @@ async def delete_page( 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. @@ -599,7 +582,6 @@ async def delete_page( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/client.py b/google/cloud/dialogflowcx_v3beta1/services/pages/client.py index 6e97331b..26f5935b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -36,8 +34,7 @@ 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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import PagesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import PagesGrpcTransport from .transports.grpc_asyncio import PagesGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class PagesClientMeta(type): _transport_registry["grpc_asyncio"] = PagesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[PagesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class PagesClient(metaclass=PagesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,10 +150,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> PagesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - PagesTransport: The transport used by the client instance. + PagesTransport: The transport used by the client + instance. """ return self._transport @@ -162,14 +162,14 @@ def transport(self) -> PagesTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -178,14 +178,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -194,14 +194,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -212,14 +212,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -230,7 +230,7 @@ def parse_page_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -241,7 +241,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -250,14 +250,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -266,7 +266,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -279,7 +279,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -290,7 +290,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -301,7 +301,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -312,7 +312,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -326,12 +326,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, PagesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the pages client. + """Instantiates the pages client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -386,9 +386,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -400,12 +401,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -420,8 +423,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -458,7 +461,6 @@ def list_pages( 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. @@ -490,10 +492,8 @@ def list_pages( # there are no flattened fields. if not isinstance(request, page.ListPagesRequest): request = page.ListPagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -541,7 +541,6 @@ def get_page( 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. @@ -590,10 +589,8 @@ def get_page( # there are no flattened fields. if not isinstance(request, page.GetPageRequest): request = page.GetPageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -641,7 +638,6 @@ def create_page( This corresponds to the ``page`` 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. @@ -690,10 +686,8 @@ def create_page( # there are no flattened fields. if not isinstance(request, gcdc_page.CreatePageRequest): request = gcdc_page.CreatePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if page is not None: @@ -720,7 +714,7 @@ def update_page( request: gcdc_page.UpdatePageRequest = None, *, page: gcdc_page.Page = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -744,7 +738,6 @@ def update_page( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -793,10 +786,8 @@ def update_page( # there are no flattened fields. if not isinstance(request, gcdc_page.UpdatePageRequest): request = gcdc_page.UpdatePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if page is not None: request.page = page if update_mask is not None: @@ -842,7 +833,6 @@ def delete_page( 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. @@ -865,10 +855,8 @@ def delete_page( # there are no flattened fields. if not isinstance(request, page.DeletePageRequest): request = page.DeletePageRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py index c075da86..1f58da55 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py index de980d7b..fff7089d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py index 75ba8065..34fa8cf8 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class PagesTransport(abc.ABC): """Abstract transport class for Pages.""" @@ -48,21 +58,24 @@ class PagesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,44 +191,39 @@ def _prep_wrapped_messages(self, client_info): @property def list_pages( self, - ) -> typing.Callable[ + ) -> Callable[ [page.ListPagesRequest], - typing.Union[page.ListPagesResponse, typing.Awaitable[page.ListPagesResponse]], + Union[page.ListPagesResponse, Awaitable[page.ListPagesResponse]], ]: raise NotImplementedError() @property def get_page( self, - ) -> typing.Callable[ - [page.GetPageRequest], typing.Union[page.Page, typing.Awaitable[page.Page]] - ]: + ) -> Callable[[page.GetPageRequest], Union[page.Page, Awaitable[page.Page]]]: raise NotImplementedError() @property def create_page( self, - ) -> typing.Callable[ - [gcdc_page.CreatePageRequest], - typing.Union[gcdc_page.Page, typing.Awaitable[gcdc_page.Page]], + ) -> Callable[ + [gcdc_page.CreatePageRequest], Union[gcdc_page.Page, Awaitable[gcdc_page.Page]] ]: raise NotImplementedError() @property def update_page( self, - ) -> typing.Callable[ - [gcdc_page.UpdatePageRequest], - typing.Union[gcdc_page.Page, typing.Awaitable[gcdc_page.Page]], + ) -> Callable[ + [gcdc_page.UpdatePageRequest], Union[gcdc_page.Page, Awaitable[gcdc_page.Page]] ]: raise NotImplementedError() @property def delete_page( self, - ) -> typing.Callable[ - [page.DeletePageRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ) -> Callable[ + [page.DeletePageRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py index e9879286..c217af1f 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 page from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PagesTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -348,7 +321,7 @@ def update_page(self) -> Callable[[gcdc_page.UpdatePageRequest], gcdc_page.Page] return self._stubs["update_page"] @property - def delete_page(self) -> Callable[[page.DeletePageRequest], empty.Empty]: + def delete_page(self) -> Callable[[page.DeletePageRequest], empty_pb2.Empty]: r"""Return a callable for the delete page method over gRPC. Deletes the specified page. @@ -367,7 +340,7 @@ def delete_page(self) -> Callable[[page.DeletePageRequest], empty.Empty]: self._stubs["delete_page"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage", request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_page"] 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 57bd8b7b..a38bc8c4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/pages/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import PagesTransport, DEFAULT_CLIENT_INFO from .grpc import PagesGrpcTransport @@ -56,7 +53,7 @@ class PagesGrpcAsyncIOTransport(PagesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -358,7 +330,9 @@ def update_page( return self._stubs["update_page"] @property - def delete_page(self) -> Callable[[page.DeletePageRequest], Awaitable[empty.Empty]]: + def delete_page( + self, + ) -> Callable[[page.DeletePageRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete page method over gRPC. Deletes the specified page. @@ -377,7 +351,7 @@ def delete_page(self) -> Callable[[page.DeletePageRequest], Awaitable[empty.Empt self._stubs["delete_page"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Pages/DeletePage", request_serializer=page.DeletePageRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_page"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py index 66f0a799..d8b471f4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SecuritySettingsServiceClient from .async_client import SecuritySettingsServiceAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/async_client.py index 72c613ab..e5537908 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import pagers @@ -33,8 +31,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport from .client import SecuritySettingsServiceClient @@ -54,33 +51,28 @@ class SecuritySettingsServiceAsyncClient: parse_security_settings_path = staticmethod( SecuritySettingsServiceClient.parse_security_settings_path ) - common_billing_account_path = staticmethod( SecuritySettingsServiceClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SecuritySettingsServiceClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SecuritySettingsServiceClient.common_folder_path) parse_common_folder_path = staticmethod( SecuritySettingsServiceClient.parse_common_folder_path ) - common_organization_path = staticmethod( SecuritySettingsServiceClient.common_organization_path ) parse_common_organization_path = staticmethod( SecuritySettingsServiceClient.parse_common_organization_path ) - common_project_path = staticmethod( SecuritySettingsServiceClient.common_project_path ) parse_common_project_path = staticmethod( SecuritySettingsServiceClient.parse_common_project_path ) - common_location_path = staticmethod( SecuritySettingsServiceClient.common_location_path ) @@ -90,7 +82,8 @@ class SecuritySettingsServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -105,7 +98,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -122,7 +115,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecuritySettingsServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SecuritySettingsServiceTransport: The transport used by the client instance. @@ -137,12 +130,12 @@ def transport(self) -> SecuritySettingsServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SecuritySettingsServiceTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security settings service client. + """Instantiates the security settings service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -174,7 +167,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SecuritySettingsServiceClient( credentials=credentials, transport=transport, @@ -214,7 +206,6 @@ async def create_security_settings( This corresponds to the ``security_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -245,7 +236,6 @@ async def create_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if security_settings is not None: @@ -295,7 +285,6 @@ async def get_security_settings( 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. @@ -326,7 +315,6 @@ async def get_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -355,7 +343,7 @@ async def update_security_settings( request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -382,7 +370,6 @@ async def update_security_settings( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -413,7 +400,6 @@ async def update_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_settings is not None: request.security_settings = security_settings if update_mask is not None: @@ -465,7 +451,6 @@ async def list_security_settings( 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. @@ -495,7 +480,6 @@ async def list_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -550,7 +534,6 @@ async def delete_security_settings( 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. @@ -571,7 +554,6 @@ async def delete_security_settings( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 e9cce02b..f5ac51dd 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,8 +35,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SecuritySettingsServiceGrpcTransport from .transports.grpc_asyncio import SecuritySettingsServiceGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class SecuritySettingsServiceClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SecuritySettingsServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class SecuritySettingsServiceClient(metaclass=SecuritySettingsServiceClientMeta) @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,10 +153,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SecuritySettingsServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SecuritySettingsServiceTransport: The transport used by the client instance. + SecuritySettingsServiceTransport: The transport used by the client + instance. """ return self._transport @@ -165,14 +165,14 @@ def transport(self) -> SecuritySettingsServiceTransport: def security_settings_path( project: str, location: str, security_settings: str, ) -> str: - """Return a fully-qualified security_settings string.""" + """Returns a fully-qualified security_settings string.""" return "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @staticmethod def parse_security_settings_path(path: str) -> Dict[str, str]: - """Parse a security_settings path into its component segments.""" + """Parses a security_settings path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/securitySettings/(?P.+?)$", path, @@ -181,7 +181,7 @@ def parse_security_settings_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -194,7 +194,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -205,7 +205,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -216,7 +216,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -227,7 +227,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -241,12 +241,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SecuritySettingsServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the security settings service client. + """Instantiates the security settings service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -301,9 +301,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -315,12 +316,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -335,8 +338,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -383,7 +386,6 @@ def create_security_settings( This corresponds to the ``security_settings`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -418,10 +420,8 @@ def create_security_settings( request, gcdc_security_settings.CreateSecuritySettingsRequest ): request = gcdc_security_settings.CreateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if security_settings is not None: @@ -467,7 +467,6 @@ def get_security_settings( 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. @@ -500,10 +499,8 @@ def get_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.GetSecuritySettingsRequest): request = security_settings.GetSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -528,7 +525,7 @@ def update_security_settings( request: gcdc_security_settings.UpdateSecuritySettingsRequest = None, *, security_settings: gcdc_security_settings.SecuritySettings = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -555,7 +552,6 @@ def update_security_settings( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -590,10 +586,8 @@ def update_security_settings( request, gcdc_security_settings.UpdateSecuritySettingsRequest ): request = gcdc_security_settings.UpdateSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if security_settings is not None: request.security_settings = security_settings if update_mask is not None: @@ -641,7 +635,6 @@ def list_security_settings( 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. @@ -673,10 +666,8 @@ def list_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.ListSecuritySettingsRequest): request = security_settings.ListSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -727,7 +718,6 @@ def delete_security_settings( 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. @@ -750,10 +740,8 @@ def delete_security_settings( # there are no flattened fields. if not isinstance(request, security_settings.DeleteSecuritySettingsRequest): request = security_settings.DeleteSecuritySettingsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py index ab825057..e2541c33 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py index fc2aea1c..8f3a8c8b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 400fd363..503d80ff 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import security_settings from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SecuritySettingsServiceTransport(abc.ABC): """Abstract transport class for SecuritySettingsService.""" @@ -50,21 +60,24 @@ class SecuritySettingsServiceTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def create_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_security_settings.CreateSecuritySettingsRequest], - typing.Union[ + Union[ gcdc_security_settings.SecuritySettings, - typing.Awaitable[gcdc_security_settings.SecuritySettings], + Awaitable[gcdc_security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def create_security_settings( @property def get_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.GetSecuritySettingsRequest], - typing.Union[ + Union[ security_settings.SecuritySettings, - typing.Awaitable[security_settings.SecuritySettings], + Awaitable[security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_security_settings( @property def update_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_security_settings.UpdateSecuritySettingsRequest], - typing.Union[ + Union[ gcdc_security_settings.SecuritySettings, - typing.Awaitable[gcdc_security_settings.SecuritySettings], + Awaitable[gcdc_security_settings.SecuritySettings], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def update_security_settings( @property def list_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.ListSecuritySettingsRequest], - typing.Union[ + Union[ security_settings.ListSecuritySettingsResponse, - typing.Awaitable[security_settings.ListSecuritySettingsResponse], + Awaitable[security_settings.ListSecuritySettingsResponse], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def list_security_settings( @property def delete_security_settings( self, - ) -> typing.Callable[ + ) -> Callable[ [security_settings.DeleteSecuritySettingsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py index 4e49c3e4..5fa72348 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/security_settings_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO @@ -54,7 +51,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -68,7 +65,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -110,7 +108,9 @@ def __init__( 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) @@ -118,70 +118,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -189,23 +169,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -213,7 +184,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -236,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -375,7 +348,7 @@ def list_security_settings( @property def delete_security_settings( self, - ) -> Callable[[security_settings.DeleteSecuritySettingsRequest], empty.Empty]: + ) -> Callable[[security_settings.DeleteSecuritySettingsRequest], empty_pb2.Empty]: r"""Return a callable for the delete security settings method over gRPC. Deletes the specified @@ -395,7 +368,7 @@ def delete_security_settings( self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings", request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_security_settings"] 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 f80dd918..df24e44e 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( security_settings as gcdc_security_settings, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SecuritySettingsServiceTransport, DEFAULT_CLIENT_INFO from .grpc import SecuritySettingsServiceGrpcTransport @@ -57,7 +54,7 @@ class SecuritySettingsServiceGrpcAsyncIOTransport(SecuritySettingsServiceTranspo def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -65,7 +62,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -84,13 +81,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -98,7 +97,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -112,7 +111,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -143,10 +143,10 @@ def __init__( 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 + 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: @@ -155,7 +155,9 @@ def __init__( 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) @@ -163,70 +165,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -234,17 +215,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -380,7 +352,7 @@ def list_security_settings( def delete_security_settings( self, ) -> Callable[ - [security_settings.DeleteSecuritySettingsRequest], Awaitable[empty.Empty] + [security_settings.DeleteSecuritySettingsRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete security settings method over gRPC. @@ -401,7 +373,7 @@ def delete_security_settings( self._stubs["delete_security_settings"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.SecuritySettingsService/DeleteSecuritySettings", request_serializer=security_settings.DeleteSecuritySettingsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_security_settings"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py index c0dca267..cbd406b4 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionEntityTypesClient from .async_client import SessionEntityTypesAsyncClient 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 0f0f9bff..a41a634b 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport from .client import SessionEntityTypesClient @@ -57,31 +54,26 @@ class SessionEntityTypesAsyncClient: parse_session_entity_type_path = staticmethod( SessionEntityTypesClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( SessionEntityTypesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionEntityTypesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionEntityTypesClient.common_folder_path) parse_common_folder_path = staticmethod( SessionEntityTypesClient.parse_common_folder_path ) - common_organization_path = staticmethod( SessionEntityTypesClient.common_organization_path ) parse_common_organization_path = staticmethod( SessionEntityTypesClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionEntityTypesClient.common_project_path) parse_common_project_path = staticmethod( SessionEntityTypesClient.parse_common_project_path ) - common_location_path = staticmethod(SessionEntityTypesClient.common_location_path) parse_common_location_path = staticmethod( SessionEntityTypesClient.parse_common_location_path @@ -89,7 +81,8 @@ class SessionEntityTypesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -104,7 +97,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -121,7 +114,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionEntityTypesTransport: The transport used by the client instance. @@ -136,12 +129,12 @@ def transport(self) -> SessionEntityTypesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionEntityTypesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -173,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -209,7 +201,6 @@ async def list_session_entity_types( 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. @@ -239,7 +230,6 @@ async def list_session_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -295,7 +285,6 @@ async def get_session_entity_type( 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. @@ -337,7 +326,6 @@ async def get_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -372,8 +360,6 @@ async def create_session_entity_type( metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest`): @@ -398,7 +384,6 @@ async def create_session_entity_type( This corresponds to the ``session_entity_type`` 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. @@ -440,7 +425,6 @@ async def create_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -471,7 +455,7 @@ async def update_session_entity_type( request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -500,7 +484,6 @@ async def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -542,7 +525,6 @@ async def update_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -597,7 +579,6 @@ async def delete_session_entity_type( 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. @@ -618,7 +599,6 @@ async def delete_session_entity_type( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 499d4724..99ea2623 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,8 +36,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionEntityTypesGrpcTransport from .transports.grpc_asyncio import SessionEntityTypesGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class SessionEntityTypesClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[SessionEntityTypesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class SessionEntityTypesClient(metaclass=SessionEntityTypesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,10 +156,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionEntityTypesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionEntityTypesTransport: The transport used by the client instance. + SessionEntityTypesTransport: The transport used by the client + instance. """ return self._transport @@ -168,7 +168,7 @@ def transport(self) -> SessionEntityTypesTransport: def session_entity_type_path( project: str, location: str, agent: str, session: str, entity_type: str, ) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -179,7 +179,7 @@ def session_entity_type_path( @staticmethod def parse_session_entity_type_path(path: str) -> Dict[str, str]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -188,7 +188,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -201,7 +201,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -212,7 +212,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -223,7 +223,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -234,7 +234,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -248,12 +248,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionEntityTypesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the session entity types client. + """Instantiates the session entity types client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -308,9 +308,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -322,12 +323,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -342,8 +345,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -386,7 +389,6 @@ def list_session_entity_types( 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. @@ -418,10 +420,8 @@ def list_session_entity_types( # there are no flattened fields. if not isinstance(request, session_entity_type.ListSessionEntityTypesRequest): request = session_entity_type.ListSessionEntityTypesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -475,7 +475,6 @@ def get_session_entity_type( 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. @@ -519,10 +518,8 @@ def get_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.GetSessionEntityTypeRequest): request = session_entity_type.GetSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -553,8 +550,6 @@ def create_session_entity_type( metadata: Sequence[Tuple[str, str]] = (), ) -> gcdc_session_entity_type.SessionEntityType: r"""Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Args: request (google.cloud.dialogflowcx_v3beta1.types.CreateSessionEntityTypeRequest): @@ -579,7 +574,6 @@ def create_session_entity_type( This corresponds to the ``session_entity_type`` 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. @@ -625,10 +619,8 @@ def create_session_entity_type( request, gcdc_session_entity_type.CreateSessionEntityTypeRequest ): request = gcdc_session_entity_type.CreateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if session_entity_type is not None: @@ -657,7 +649,7 @@ def update_session_entity_type( request: gcdc_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcdc_session_entity_type.SessionEntityType = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -686,7 +678,6 @@ def update_session_entity_type( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -732,10 +723,8 @@ def update_session_entity_type( request, gcdc_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcdc_session_entity_type.UpdateSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session_entity_type is not None: request.session_entity_type = session_entity_type if update_mask is not None: @@ -788,7 +777,6 @@ def delete_session_entity_type( 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. @@ -811,10 +799,8 @@ def delete_session_entity_type( # there are no flattened fields. if not isinstance(request, session_entity_type.DeleteSessionEntityTypeRequest): request = session_entity_type.DeleteSessionEntityTypeRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py index d602f60b..40855a66 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py index 606f9116..633fd32c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 03b9fab1..67dd7511 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import session_entity_type from google.cloud.dialogflowcx_v3beta1.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SessionEntityTypesTransport(abc.ABC): """Abstract transport class for SessionEntityTypes.""" @@ -50,21 +60,24 @@ class SessionEntityTypesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_session_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.ListSessionEntityTypesRequest], - typing.Union[ + Union[ session_entity_type.ListSessionEntityTypesResponse, - typing.Awaitable[session_entity_type.ListSessionEntityTypesResponse], + Awaitable[session_entity_type.ListSessionEntityTypesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_session_entity_types( @property def get_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.GetSessionEntityTypeRequest], - typing.Union[ + Union[ session_entity_type.SessionEntityType, - typing.Awaitable[session_entity_type.SessionEntityType], + Awaitable[session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_session_entity_type( @property def create_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcdc_session_entity_type.SessionEntityType, - typing.Awaitable[gcdc_session_entity_type.SessionEntityType], + Awaitable[gcdc_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_session_entity_type( @property def update_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcdc_session_entity_type.SessionEntityType, - typing.Awaitable[gcdc_session_entity_type.SessionEntityType], + Awaitable[gcdc_session_entity_type.SessionEntityType], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [session_entity_type.DeleteSessionEntityTypeRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py index 8ba8b9fd..7fcdd668 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/session_entity_types/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,9 @@ def __init__( 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) @@ -119,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,23 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -322,8 +295,6 @@ def create_session_entity_type( r"""Return a callable for the create session entity type method over gRPC. Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Returns: Callable[[~.CreateSessionEntityTypeRequest], @@ -375,7 +346,9 @@ def update_session_entity_type( @property def delete_session_entity_type( self, - ) -> Callable[[session_entity_type.DeleteSessionEntityTypeRequest], empty.Empty]: + ) -> Callable[ + [session_entity_type.DeleteSessionEntityTypeRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete session entity type method over gRPC. Deletes the specified session entity type. @@ -394,7 +367,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] 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 07d07354..a7f357c2 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( session_entity_type as gcdc_session_entity_type, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import SessionEntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import SessionEntityTypesGrpcTransport @@ -58,7 +55,7 @@ class SessionEntityTypesGrpcAsyncIOTransport(SessionEntityTypesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -326,8 +298,6 @@ def create_session_entity_type( r"""Return a callable for the create session entity type method over gRPC. Creates a session entity type. - If the specified session entity type already exists, - overrides the session entity type. Returns: Callable[[~.CreateSessionEntityTypeRequest], @@ -380,7 +350,7 @@ def update_session_entity_type( def delete_session_entity_type( self, ) -> Callable[ - [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty.Empty] + [session_entity_type.DeleteSessionEntityTypeRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete session entity type method over gRPC. @@ -400,7 +370,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.SessionEntityTypes/DeleteSessionEntityType", request_serializer=session_entity_type.DeleteSessionEntityTypeRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_session_entity_type"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py index 3b2a59a9..0adeafb9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import SessionsClient from .async_client import SessionsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py index 36786e90..855a00e9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -31,16 +29,15 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 audio_config from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import session - from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -80,31 +77,27 @@ class SessionsAsyncClient: ) webhook_path = staticmethod(SessionsClient.webhook_path) parse_webhook_path = staticmethod(SessionsClient.parse_webhook_path) - common_billing_account_path = staticmethod( SessionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( SessionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(SessionsClient.common_folder_path) parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path) - common_organization_path = staticmethod(SessionsClient.common_organization_path) parse_common_organization_path = staticmethod( SessionsClient.parse_common_organization_path ) - common_project_path = staticmethod(SessionsClient.common_project_path) parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path) - common_location_path = staticmethod(SessionsClient.common_location_path) parse_common_location_path = staticmethod(SessionsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -119,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -136,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: SessionsTransport: The transport used by the client instance. @@ -150,12 +143,12 @@ def transport(self) -> SessionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, SessionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -187,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -215,7 +207,6 @@ async def detect_intent( Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.DetectIntentRequest`): 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. timeout (float): The timeout for this request. @@ -229,7 +220,6 @@ async def detect_intent( """ # Create or coerce a protobuf request object. - request = session.DetectIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -240,7 +230,10 @@ async def detect_intent( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, ), default_timeout=220.0, client_info=DEFAULT_CLIENT_INFO, @@ -329,7 +322,14 @@ def streaming_detect_intent( Each recognition_result represents a more complete transcript of what the user said. The last recognition_result has is_final set to true. - 2. The last message contains detect_intent_response. + 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. """ @@ -361,7 +361,6 @@ async def match_intent( Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest`): The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -373,7 +372,6 @@ async def match_intent( Response of [MatchIntent][]. """ # Create or coerce a protobuf request object. - request = session.MatchIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -415,7 +413,6 @@ async def fulfill_intent( Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest`): The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,7 +424,6 @@ async def fulfill_intent( Response of [FulfillIntent][] """ # Create or coerce a protobuf request object. - request = session.FulfillIntentRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py index cb983edb..f0e8cf45 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -33,10 +31,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -45,7 +43,6 @@ 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 - from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -64,7 +61,7 @@ class SessionsClientMeta(type): _transport_registry["grpc_asyncio"] = SessionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[SessionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -91,7 +88,8 @@ class SessionsClient(metaclass=SessionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -125,7 +123,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -142,7 +141,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -161,10 +160,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> SessionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - SessionsTransport: The transport used by the client instance. + SessionsTransport: The transport used by the client + instance. """ return self._transport @@ -172,14 +172,14 @@ def transport(self) -> SessionsTransport: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -188,14 +188,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -204,14 +204,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -222,14 +222,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -238,14 +238,14 @@ def parse_page_path(path: str) -> Dict[str, str]: @staticmethod def session_path(project: str, location: str, agent: str, session: str,) -> str: - """Return a fully-qualified session string.""" + """Returns a fully-qualified session string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format( project=project, location=location, agent=agent, session=session, ) @staticmethod def parse_session_path(path: str) -> Dict[str, str]: - """Parse a session path into its component segments.""" + """Parses a session path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)$", path, @@ -256,7 +256,7 @@ def parse_session_path(path: str) -> Dict[str, str]: def session_entity_type_path( project: str, location: str, agent: str, session: str, entity_type: str, ) -> str: - """Return a fully-qualified session_entity_type string.""" + """Returns a fully-qualified session_entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -267,7 +267,7 @@ def session_entity_type_path( @staticmethod def parse_session_entity_type_path(path: str) -> Dict[str, str]: - """Parse a session_entity_type path into its component segments.""" + """Parses a session_entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/sessions/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -278,7 +278,7 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -289,7 +289,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -298,14 +298,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -314,7 +314,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -327,7 +327,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -338,7 +338,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -349,7 +349,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -360,7 +360,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -374,12 +374,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, SessionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the sessions client. + """Instantiates the sessions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -434,9 +434,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -448,12 +449,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -468,8 +471,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -504,7 +507,6 @@ def detect_intent( Args: request (google.cloud.dialogflowcx_v3beta1.types.DetectIntentRequest): 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. timeout (float): The timeout for this request. @@ -518,7 +520,6 @@ def detect_intent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.DetectIntentRequest. # There's no risk of modifying the input as we've already verified @@ -613,7 +614,14 @@ def streaming_detect_intent( Each recognition_result represents a more complete transcript of what the user said. The last recognition_result has is_final set to true. - 2. The last message contains detect_intent_response. + 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. """ @@ -641,7 +649,6 @@ def match_intent( Args: request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): The request object. Request of [MatchIntent][]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -653,7 +660,6 @@ def match_intent( Response of [MatchIntent][]. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.MatchIntentRequest. # There's no risk of modifying the input as we've already verified @@ -696,7 +702,6 @@ def fulfill_intent( Args: request (google.cloud.dialogflowcx_v3beta1.types.FulfillIntentRequest): The request object. Request of [FulfillIntent][] - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -708,7 +713,6 @@ def fulfill_intent( Response of [FulfillIntent][] """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a session.FulfillIntentRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py index 0ca6c76e..db0f7d04 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py index 3f9427e7..997984bd 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -37,6 +36,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class SessionsTransport(abc.ABC): """Abstract transport class for Sessions.""" @@ -46,21 +56,24 @@ class SessionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -69,13 +82,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -83,28 +96,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -115,7 +175,10 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=220.0, ), default_timeout=220.0, client_info=client_info, @@ -136,22 +199,20 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.DetectIntentRequest], - typing.Union[ - session.DetectIntentResponse, typing.Awaitable[session.DetectIntentResponse] - ], + Union[session.DetectIntentResponse, Awaitable[session.DetectIntentResponse]], ]: raise NotImplementedError() @property def streaming_detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.StreamingDetectIntentRequest], - typing.Union[ + Union[ session.StreamingDetectIntentResponse, - typing.Awaitable[session.StreamingDetectIntentResponse], + Awaitable[session.StreamingDetectIntentResponse], ], ]: raise NotImplementedError() @@ -159,23 +220,18 @@ def streaming_detect_intent( @property def match_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.MatchIntentRequest], - typing.Union[ - session.MatchIntentResponse, typing.Awaitable[session.MatchIntentResponse] - ], + Union[session.MatchIntentResponse, Awaitable[session.MatchIntentResponse]], ]: raise NotImplementedError() @property def fulfill_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [session.FulfillIntentRequest], - typing.Union[ - session.FulfillIntentResponse, - typing.Awaitable[session.FulfillIntentResponse], - ], + Union[session.FulfillIntentResponse, Awaitable[session.FulfillIntentResponse]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py index 91cd771e..74179943 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) 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 99dcbcb2..c3486303 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/sessions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -56,7 +53,7 @@ class SessionsGrpcAsyncIOTransport(SessionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py index 77517b44..359c8900 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TestCasesClient from .async_client import TestCasesAsyncClient 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 fd2e5649..a67d01ce 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,9 +31,8 @@ from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers from google.cloud.dialogflowcx_v3beta1.types import test_case from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport from .client import TestCasesClient @@ -78,25 +75,20 @@ class TestCasesAsyncClient: ) webhook_path = staticmethod(TestCasesClient.webhook_path) parse_webhook_path = staticmethod(TestCasesClient.parse_webhook_path) - common_billing_account_path = staticmethod( TestCasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TestCasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TestCasesClient.common_folder_path) parse_common_folder_path = staticmethod(TestCasesClient.parse_common_folder_path) - common_organization_path = staticmethod(TestCasesClient.common_organization_path) parse_common_organization_path = staticmethod( TestCasesClient.parse_common_organization_path ) - common_project_path = staticmethod(TestCasesClient.common_project_path) parse_common_project_path = staticmethod(TestCasesClient.parse_common_project_path) - common_location_path = staticmethod(TestCasesClient.common_location_path) parse_common_location_path = staticmethod( TestCasesClient.parse_common_location_path @@ -104,7 +96,8 @@ class TestCasesAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -119,7 +112,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -136,7 +129,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TestCasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TestCasesTransport: The transport used by the client instance. @@ -150,12 +143,12 @@ def transport(self) -> TestCasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TestCasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the test cases client. + """Instantiates the test cases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -187,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TestCasesClient( credentials=credentials, transport=transport, @@ -217,7 +209,6 @@ async def list_test_cases( 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. @@ -247,7 +238,6 @@ async def list_test_cases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -299,7 +289,6 @@ async def batch_delete_test_cases( 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. @@ -320,7 +309,6 @@ async def batch_delete_test_cases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -365,7 +353,6 @@ async def get_test_case( 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. @@ -390,7 +377,6 @@ async def get_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -442,7 +428,6 @@ async def create_test_case( This corresponds to the ``test_case`` 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. @@ -467,7 +452,6 @@ async def create_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if test_case is not None: @@ -498,7 +482,7 @@ async def update_test_case( request: gcdc_test_case.UpdateTestCaseRequest = None, *, test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -525,7 +509,6 @@ async def update_test_case( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -550,7 +533,6 @@ async def update_test_case( # If we have keyword arguments corresponding to fields on the # request, apply these. - if test_case is not None: request.test_case = test_case if update_mask is not None: @@ -592,7 +574,6 @@ async def run_test_case( request (:class:`google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -610,7 +591,6 @@ async def run_test_case( """ # Create or coerce a protobuf request object. - request = test_case.RunTestCaseRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -655,7 +635,6 @@ async def batch_run_test_cases( request (:class:`google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -673,7 +652,6 @@ async def batch_run_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.BatchRunTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -718,7 +696,6 @@ async def calculate_coverage( request (:class:`google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -732,7 +709,6 @@ async def calculate_coverage( """ # Create or coerce a protobuf request object. - request = test_case.CalculateCoverageRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -772,7 +748,6 @@ async def import_test_cases( request (:class:`google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -790,7 +765,6 @@ async def import_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.ImportTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -837,7 +811,6 @@ async def export_test_cases( request (:class:`google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest`): 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, should be retried. timeout (float): The timeout for this request. @@ -855,7 +828,6 @@ async def export_test_cases( """ # Create or coerce a protobuf request object. - request = test_case.ExportTestCasesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -910,7 +882,6 @@ async def list_test_case_results( 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. @@ -940,7 +911,6 @@ async def list_test_case_results( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -970,6 +940,77 @@ async def list_test_case_results( # Done; return the response. return response + async def get_test_case_result( + self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = 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`): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + name (:class:`str`): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + 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.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # 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 = test_case.GetTestCaseResultRequest(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_test_case_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py index 638793ed..3172ea9c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -37,9 +35,8 @@ from google.cloud.dialogflowcx_v3beta1.services.test_cases import pagers from google.cloud.dialogflowcx_v3beta1.types import test_case from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import TestCasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TestCasesGrpcTransport from .transports.grpc_asyncio import TestCasesGrpcAsyncIOTransport @@ -58,7 +55,7 @@ class TestCasesClientMeta(type): _transport_registry["grpc_asyncio"] = TestCasesGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[TestCasesTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -84,7 +81,8 @@ class TestCasesClient(metaclass=TestCasesClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -118,7 +116,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -135,7 +134,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -154,23 +153,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TestCasesTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TestCasesTransport: The transport used by the client instance. + TestCasesTransport: The transport used by the client + instance. """ return self._transport @staticmethod def agent_path(project: str, location: str, agent: str,) -> str: - """Return a fully-qualified agent string.""" + """Returns a fully-qualified agent string.""" return "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @staticmethod def parse_agent_path(path: str) -> Dict[str, str]: - """Parse a agent path into its component segments.""" + """Parses a agent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", path, @@ -181,14 +181,14 @@ def parse_agent_path(path: str) -> Dict[str, str]: def entity_type_path( project: str, location: str, agent: str, entity_type: str, ) -> str: - """Return a fully-qualified entity_type string.""" + """Returns a fully-qualified entity_type string.""" return "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @staticmethod def parse_entity_type_path(path: str) -> Dict[str, str]: - """Parse a entity_type path into its component segments.""" + """Parses a entity_type path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/entityTypes/(?P.+?)$", path, @@ -199,14 +199,14 @@ def parse_entity_type_path(path: str) -> Dict[str, str]: def environment_path( project: str, location: str, agent: str, environment: str, ) -> str: - """Return a fully-qualified environment string.""" + """Returns a fully-qualified environment string.""" return "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @staticmethod def parse_environment_path(path: str) -> Dict[str, str]: - """Parse a environment path into its component segments.""" + """Parses a environment path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/environments/(?P.+?)$", path, @@ -215,14 +215,14 @@ def parse_environment_path(path: str) -> Dict[str, str]: @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -231,14 +231,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -249,14 +249,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -265,14 +265,14 @@ def parse_page_path(path: str) -> Dict[str, str]: @staticmethod def test_case_path(project: str, location: str, agent: str, test_case: str,) -> str: - """Return a fully-qualified test_case string.""" + """Returns a fully-qualified test_case string.""" return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( project=project, location=location, agent=agent, test_case=test_case, ) @staticmethod def parse_test_case_path(path: str) -> Dict[str, str]: - """Parse a test_case path into its component segments.""" + """Parses a test_case path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)$", path, @@ -283,7 +283,7 @@ def parse_test_case_path(path: str) -> Dict[str, str]: def test_case_result_path( project: str, location: str, agent: str, test_case: str, result: str, ) -> str: - """Return a fully-qualified test_case_result string.""" + """Returns a fully-qualified test_case_result string.""" return "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -294,7 +294,7 @@ def test_case_result_path( @staticmethod def parse_test_case_result_path(path: str) -> Dict[str, str]: - """Parse a test_case_result path into its component segments.""" + """Parses a test_case_result path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/testCases/(?P.+?)/results/(?P.+?)$", path, @@ -305,7 +305,7 @@ def parse_test_case_result_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -316,7 +316,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -325,14 +325,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -341,7 +341,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -354,7 +354,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -365,7 +365,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -376,7 +376,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -387,7 +387,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -401,12 +401,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TestCasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the test cases client. + """Instantiates the test cases client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -461,9 +461,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -475,12 +476,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -495,8 +498,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -533,7 +536,6 @@ def list_test_cases( 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. @@ -565,10 +567,8 @@ def list_test_cases( # there are no flattened fields. if not isinstance(request, test_case.ListTestCasesRequest): request = test_case.ListTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -616,7 +616,6 @@ def batch_delete_test_cases( 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. @@ -639,10 +638,8 @@ def batch_delete_test_cases( # there are no flattened fields. if not isinstance(request, test_case.BatchDeleteTestCasesRequest): request = test_case.BatchDeleteTestCasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -683,7 +680,6 @@ def get_test_case( 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. @@ -710,10 +706,8 @@ def get_test_case( # there are no flattened fields. if not isinstance(request, test_case.GetTestCaseRequest): request = test_case.GetTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -761,7 +755,6 @@ def create_test_case( This corresponds to the ``test_case`` 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. @@ -788,10 +781,8 @@ def create_test_case( # there are no flattened fields. if not isinstance(request, gcdc_test_case.CreateTestCaseRequest): request = gcdc_test_case.CreateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if test_case is not None: @@ -818,7 +809,7 @@ def update_test_case( request: gcdc_test_case.UpdateTestCaseRequest = None, *, test_case: gcdc_test_case.TestCase = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -845,7 +836,6 @@ def update_test_case( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -872,10 +862,8 @@ def update_test_case( # there are no flattened fields. if not isinstance(request, gcdc_test_case.UpdateTestCaseRequest): request = gcdc_test_case.UpdateTestCaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if test_case is not None: request.test_case = test_case if update_mask is not None: @@ -913,7 +901,6 @@ def run_test_case( request (google.cloud.dialogflowcx_v3beta1.types.RunTestCaseRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -931,7 +918,6 @@ def run_test_case( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.RunTestCaseRequest. # There's no risk of modifying the input as we've already verified @@ -977,7 +963,6 @@ def batch_run_test_cases( request (google.cloud.dialogflowcx_v3beta1.types.BatchRunTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -995,7 +980,6 @@ def batch_run_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.BatchRunTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1041,7 +1025,6 @@ def calculate_coverage( request (google.cloud.dialogflowcx_v3beta1.types.CalculateCoverageRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1055,7 +1038,6 @@ def calculate_coverage( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.CalculateCoverageRequest. # There's no risk of modifying the input as we've already verified @@ -1096,7 +1078,6 @@ def import_test_cases( request (google.cloud.dialogflowcx_v3beta1.types.ImportTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1114,7 +1095,6 @@ def import_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.ImportTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1162,7 +1142,6 @@ def export_test_cases( request (google.cloud.dialogflowcx_v3beta1.types.ExportTestCasesRequest): 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, should be retried. timeout (float): The timeout for this request. @@ -1180,7 +1159,6 @@ def export_test_cases( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a test_case.ExportTestCasesRequest. # There's no risk of modifying the input as we've already verified @@ -1236,7 +1214,6 @@ def list_test_case_results( 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. @@ -1268,10 +1245,8 @@ def list_test_case_results( # there are no flattened fields. if not isinstance(request, test_case.ListTestCaseResultsRequest): request = test_case.ListTestCaseResultsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1297,6 +1272,77 @@ def list_test_case_results( # Done; return the response. return response + def get_test_case_result( + self, + request: test_case.GetTestCaseResultRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> test_case.TestCaseResult: + r"""Gets a test case result. + + Args: + request (google.cloud.dialogflowcx_v3beta1.types.GetTestCaseResultRequest): + The request object. The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + + 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.TestCaseResult: + Represents a result from running a + test case in an agent environment. + + """ + # 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 test_case.GetTestCaseResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, test_case.GetTestCaseResultRequest): + request = test_case.GetTestCaseResultRequest(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_test_case_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py index e16aa200..49962f70 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py index 0c356952..caa2815b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 3628c659..938dea49 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import test_case from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TestCasesTransport(abc.ABC): """Abstract transport class for TestCases.""" @@ -50,21 +60,24 @@ class TestCasesTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -152,6 +212,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.get_test_case_result: gapic_v1.method.wrap_method( + self.get_test_case_result, + default_timeout=None, + client_info=client_info, + ), } @property @@ -162,11 +227,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ListTestCasesRequest], - typing.Union[ - test_case.ListTestCasesResponse, - typing.Awaitable[test_case.ListTestCasesResponse], + Union[ + test_case.ListTestCasesResponse, Awaitable[test_case.ListTestCasesResponse] ], ]: raise NotImplementedError() @@ -174,69 +238,65 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.BatchDeleteTestCasesRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def get_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.GetTestCaseRequest], - typing.Union[test_case.TestCase, typing.Awaitable[test_case.TestCase]], + Union[test_case.TestCase, Awaitable[test_case.TestCase]], ]: raise NotImplementedError() @property def create_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_test_case.CreateTestCaseRequest], - typing.Union[ - gcdc_test_case.TestCase, typing.Awaitable[gcdc_test_case.TestCase] - ], + Union[gcdc_test_case.TestCase, Awaitable[gcdc_test_case.TestCase]], ]: raise NotImplementedError() @property def update_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_test_case.UpdateTestCaseRequest], - typing.Union[ - gcdc_test_case.TestCase, typing.Awaitable[gcdc_test_case.TestCase] - ], + Union[gcdc_test_case.TestCase, Awaitable[gcdc_test_case.TestCase]], ]: raise NotImplementedError() @property def run_test_case( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.RunTestCaseRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_run_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.BatchRunTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def calculate_coverage( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.CalculateCoverageRequest], - typing.Union[ + Union[ test_case.CalculateCoverageResponse, - typing.Awaitable[test_case.CalculateCoverageResponse], + Awaitable[test_case.CalculateCoverageResponse], ], ]: raise NotImplementedError() @@ -244,32 +304,41 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ImportTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def export_test_cases( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ExportTestCasesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def list_test_case_results( self, - ) -> typing.Callable[ + ) -> Callable[ [test_case.ListTestCaseResultsRequest], - typing.Union[ + Union[ test_case.ListTestCaseResultsResponse, - typing.Awaitable[test_case.ListTestCaseResultsResponse], + Awaitable[test_case.ListTestCaseResultsResponse], ], ]: raise NotImplementedError() + @property + def get_test_case_result( + self, + ) -> Callable[ + [test_case.GetTestCaseResultRequest], + Union[test_case.TestCaseResult, Awaitable[test_case.TestCaseResult]], + ]: + raise NotImplementedError() + __all__ = ("TestCasesTransport",) 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 0a25b5ad..0177d4dd 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/test_cases/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 test_case from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import TestCasesTransport, DEFAULT_CLIENT_INFO @@ -56,7 +53,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -70,7 +67,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -112,7 +110,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -120,70 +121,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -191,24 +172,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -216,7 +187,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -239,13 +210,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -298,7 +271,7 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> Callable[[test_case.BatchDeleteTestCasesRequest], empty.Empty]: + ) -> Callable[[test_case.BatchDeleteTestCasesRequest], empty_pb2.Empty]: r"""Return a callable for the batch delete test cases method over gRPC. Batch deletes test cases. @@ -317,7 +290,7 @@ def batch_delete_test_cases( self._stubs["batch_delete_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases", request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["batch_delete_test_cases"] @@ -402,7 +375,7 @@ def update_test_case( @property def run_test_case( self, - ) -> Callable[[test_case.RunTestCaseRequest], operations.Operation]: + ) -> Callable[[test_case.RunTestCaseRequest], operations_pb2.Operation]: r"""Return a callable for the run test case method over gRPC. Kicks off a test case run. @@ -421,14 +394,14 @@ def run_test_case( self._stubs["run_test_case"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase", request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_test_case"] @property def batch_run_test_cases( self, - ) -> Callable[[test_case.BatchRunTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.BatchRunTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the batch run test cases method over gRPC. Kicks off a batch run of test cases. @@ -447,7 +420,7 @@ def batch_run_test_cases( self._stubs["batch_run_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases", request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_run_test_cases"] @@ -482,7 +455,7 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> Callable[[test_case.ImportTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.ImportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the import test cases method over gRPC. Imports the test cases from a Cloud Storage bucket or @@ -504,14 +477,14 @@ def import_test_cases( self._stubs["import_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases", request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_test_cases"] @property def export_test_cases( self, - ) -> Callable[[test_case.ExportTestCasesRequest], operations.Operation]: + ) -> Callable[[test_case.ExportTestCasesRequest], operations_pb2.Operation]: r"""Return a callable for the export test cases method over gRPC. Exports the test cases under the agent to a Cloud @@ -532,7 +505,7 @@ def export_test_cases( self._stubs["export_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases", request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_test_cases"] @@ -564,5 +537,31 @@ def list_test_case_results( ) return self._stubs["list_test_case_results"] + @property + def get_test_case_result( + self, + ) -> Callable[[test_case.GetTestCaseResultRequest], test_case.TestCaseResult]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + ~.TestCaseResult]: + 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_test_case_result" not in self._stubs: + self._stubs["get_test_case_result"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult", + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs["get_test_case_result"] + __all__ = ("TestCasesGrpcTransport",) 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 2b33fcea..6b687ebd 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import test_case from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import TestCasesTransport, DEFAULT_CLIENT_INFO from .grpc import TestCasesGrpcTransport @@ -59,7 +56,7 @@ class TestCasesGrpcAsyncIOTransport(TestCasesTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -67,7 +64,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -86,13 +83,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -100,7 +99,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -114,7 +113,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -145,10 +145,10 @@ def __init__( 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 + 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: @@ -157,7 +157,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -165,70 +168,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -236,18 +218,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -306,7 +278,7 @@ def list_test_cases( @property def batch_delete_test_cases( self, - ) -> Callable[[test_case.BatchDeleteTestCasesRequest], Awaitable[empty.Empty]]: + ) -> Callable[[test_case.BatchDeleteTestCasesRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the batch delete test cases method over gRPC. Batch deletes test cases. @@ -325,7 +297,7 @@ def batch_delete_test_cases( self._stubs["batch_delete_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchDeleteTestCases", request_serializer=test_case.BatchDeleteTestCasesRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["batch_delete_test_cases"] @@ -414,7 +386,7 @@ def update_test_case( @property def run_test_case( self, - ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations.Operation]]: + ) -> Callable[[test_case.RunTestCaseRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the run test case method over gRPC. Kicks off a test case run. @@ -433,7 +405,7 @@ def run_test_case( self._stubs["run_test_case"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/RunTestCase", request_serializer=test_case.RunTestCaseRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["run_test_case"] @@ -441,7 +413,7 @@ def run_test_case( def batch_run_test_cases( self, ) -> Callable[ - [test_case.BatchRunTestCasesRequest], Awaitable[operations.Operation] + [test_case.BatchRunTestCasesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch run test cases method over gRPC. @@ -461,7 +433,7 @@ def batch_run_test_cases( self._stubs["batch_run_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/BatchRunTestCases", request_serializer=test_case.BatchRunTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_run_test_cases"] @@ -497,7 +469,9 @@ def calculate_coverage( @property def import_test_cases( self, - ) -> Callable[[test_case.ImportTestCasesRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [test_case.ImportTestCasesRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the import test cases method over gRPC. Imports the test cases from a Cloud Storage bucket or @@ -519,14 +493,16 @@ def import_test_cases( self._stubs["import_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/ImportTestCases", request_serializer=test_case.ImportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_test_cases"] @property def export_test_cases( self, - ) -> Callable[[test_case.ExportTestCasesRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [test_case.ExportTestCasesRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the export test cases method over gRPC. Exports the test cases under the agent to a Cloud @@ -547,7 +523,7 @@ def export_test_cases( self._stubs["export_test_cases"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TestCases/ExportTestCases", request_serializer=test_case.ExportTestCasesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_test_cases"] @@ -580,5 +556,33 @@ def list_test_case_results( ) return self._stubs["list_test_case_results"] + @property + def get_test_case_result( + self, + ) -> Callable[ + [test_case.GetTestCaseResultRequest], Awaitable[test_case.TestCaseResult] + ]: + r"""Return a callable for the get test case result method over gRPC. + + Gets a test case result. + + Returns: + Callable[[~.GetTestCaseResultRequest], + Awaitable[~.TestCaseResult]]: + 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_test_case_result" not in self._stubs: + self._stubs["get_test_case_result"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.cx.v3beta1.TestCases/GetTestCaseResult", + request_serializer=test_case.GetTestCaseResultRequest.serialize, + response_deserializer=test_case.TestCaseResult.deserialize, + ) + return self._stubs["get_test_case_result"] + __all__ = ("TestCasesGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py index af48a31a..c5098c8b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import TransitionRouteGroupsClient from .async_client import TransitionRouteGroupsAsyncClient 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 a10bed56..ebd3a056 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport from .client import TransitionRouteGroupsClient @@ -65,31 +62,26 @@ class TransitionRouteGroupsAsyncClient: ) webhook_path = staticmethod(TransitionRouteGroupsClient.webhook_path) parse_webhook_path = staticmethod(TransitionRouteGroupsClient.parse_webhook_path) - common_billing_account_path = staticmethod( TransitionRouteGroupsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( TransitionRouteGroupsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(TransitionRouteGroupsClient.common_folder_path) parse_common_folder_path = staticmethod( TransitionRouteGroupsClient.parse_common_folder_path ) - common_organization_path = staticmethod( TransitionRouteGroupsClient.common_organization_path ) parse_common_organization_path = staticmethod( TransitionRouteGroupsClient.parse_common_organization_path ) - common_project_path = staticmethod(TransitionRouteGroupsClient.common_project_path) parse_common_project_path = staticmethod( TransitionRouteGroupsClient.parse_common_project_path ) - common_location_path = staticmethod( TransitionRouteGroupsClient.common_location_path ) @@ -99,7 +91,8 @@ class TransitionRouteGroupsAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -114,7 +107,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -131,7 +124,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TransitionRouteGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: TransitionRouteGroupsTransport: The transport used by the client instance. @@ -146,12 +139,12 @@ def transport(self) -> TransitionRouteGroupsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, TransitionRouteGroupsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the transition route groups client. + """Instantiates the transition route groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -183,7 +176,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = TransitionRouteGroupsClient( credentials=credentials, transport=transport, @@ -215,7 +207,6 @@ async def list_transition_route_groups( 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. @@ -245,7 +236,6 @@ async def list_transition_route_groups( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -300,7 +290,6 @@ async def get_transition_route_group( 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. @@ -329,7 +318,6 @@ async def get_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -387,7 +375,6 @@ async def create_transition_route_group( This corresponds to the ``transition_route_group`` 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. @@ -416,7 +403,6 @@ async def create_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if transition_route_group is not None: @@ -447,7 +433,7 @@ async def update_transition_route_group( request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -473,7 +459,6 @@ async def update_transition_route_group( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -502,7 +487,6 @@ async def update_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if transition_route_group is not None: request.transition_route_group = transition_route_group if update_mask is not None: @@ -555,7 +539,6 @@ async def delete_transition_route_group( 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. @@ -576,7 +559,6 @@ async def delete_transition_route_group( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 ea13b5eb..9cab10af 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,8 +36,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import TransitionRouteGroupsGrpcTransport from .transports.grpc_asyncio import TransitionRouteGroupsGrpcAsyncIOTransport @@ -62,7 +59,7 @@ class TransitionRouteGroupsClientMeta(type): def get_transport_class( cls, label: str = None, ) -> Type[TransitionRouteGroupsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -87,7 +84,8 @@ class TransitionRouteGroupsClient(metaclass=TransitionRouteGroupsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -121,7 +119,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -138,7 +137,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -157,23 +156,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> TransitionRouteGroupsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - TransitionRouteGroupsTransport: The transport used by the client instance. + TransitionRouteGroupsTransport: The transport used by the client + instance. """ return self._transport @staticmethod def flow_path(project: str, location: str, agent: str, flow: str,) -> str: - """Return a fully-qualified flow string.""" + """Returns a fully-qualified flow string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @staticmethod def parse_flow_path(path: str) -> Dict[str, str]: - """Parse a flow path into its component segments.""" + """Parses a flow path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)$", path, @@ -182,14 +182,14 @@ def parse_flow_path(path: str) -> Dict[str, str]: @staticmethod def intent_path(project: str, location: str, agent: str, intent: str,) -> str: - """Return a fully-qualified intent string.""" + """Returns a fully-qualified intent string.""" return "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @staticmethod def parse_intent_path(path: str) -> Dict[str, str]: - """Parse a intent path into its component segments.""" + """Parses a intent path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/intents/(?P.+?)$", path, @@ -200,14 +200,14 @@ def parse_intent_path(path: str) -> Dict[str, str]: def page_path( project: str, location: str, agent: str, flow: str, page: str, ) -> str: - """Return a fully-qualified page string.""" + """Returns a fully-qualified page string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @staticmethod def parse_page_path(path: str) -> Dict[str, str]: - """Parse a page path into its component segments.""" + """Parses a page path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/pages/(?P.+?)$", path, @@ -218,7 +218,7 @@ def parse_page_path(path: str) -> Dict[str, str]: def transition_route_group_path( project: str, location: str, agent: str, flow: str, transition_route_group: str, ) -> str: - """Return a fully-qualified transition_route_group string.""" + """Returns a fully-qualified transition_route_group string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -229,7 +229,7 @@ def transition_route_group_path( @staticmethod def parse_transition_route_group_path(path: str) -> Dict[str, str]: - """Parse a transition_route_group path into its component segments.""" + """Parses a transition_route_group path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/transitionRouteGroups/(?P.+?)$", path, @@ -238,14 +238,14 @@ def parse_transition_route_group_path(path: str) -> Dict[str, str]: @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -254,7 +254,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -267,7 +267,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -278,7 +278,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -289,7 +289,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -300,7 +300,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -314,12 +314,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, TransitionRouteGroupsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the transition route groups client. + """Instantiates the transition route groups client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -374,9 +374,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -388,12 +389,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -408,8 +411,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -448,7 +451,6 @@ def list_transition_route_groups( 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. @@ -482,10 +484,8 @@ def list_transition_route_groups( request, transition_route_group.ListTransitionRouteGroupsRequest ): request = transition_route_group.ListTransitionRouteGroupsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -538,7 +538,6 @@ def get_transition_route_group( 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. @@ -571,10 +570,8 @@ def get_transition_route_group( request, transition_route_group.GetTransitionRouteGroupRequest ): request = transition_route_group.GetTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -630,7 +627,6 @@ def create_transition_route_group( This corresponds to the ``transition_route_group`` 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. @@ -665,10 +661,8 @@ def create_transition_route_group( request = gcdc_transition_route_group.CreateTransitionRouteGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if transition_route_group is not None: @@ -697,7 +691,7 @@ def update_transition_route_group( request: gcdc_transition_route_group.UpdateTransitionRouteGroupRequest = None, *, transition_route_group: gcdc_transition_route_group.TransitionRouteGroup = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -723,7 +717,6 @@ def update_transition_route_group( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -758,10 +751,8 @@ def update_transition_route_group( request = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest( request ) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if transition_route_group is not None: request.transition_route_group = transition_route_group if update_mask is not None: @@ -812,7 +803,6 @@ def delete_transition_route_group( 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. @@ -837,10 +827,8 @@ def delete_transition_route_group( request, transition_route_group.DeleteTransitionRouteGroupRequest ): request = transition_route_group.DeleteTransitionRouteGroupRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py index 384b0fab..72aab26b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -121,7 +119,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py index eb2e1618..1f1275f6 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type 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 2693947d..e7287904 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import transition_route_group from google.cloud.dialogflowcx_v3beta1.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class TransitionRouteGroupsTransport(abc.ABC): """Abstract transport class for TransitionRouteGroups.""" @@ -50,21 +60,24 @@ class TransitionRouteGroupsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_transition_route_groups( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.ListTransitionRouteGroupsRequest], - typing.Union[ + Union[ transition_route_group.ListTransitionRouteGroupsResponse, - typing.Awaitable[transition_route_group.ListTransitionRouteGroupsResponse], + Awaitable[transition_route_group.ListTransitionRouteGroupsResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_transition_route_groups( @property def get_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.GetTransitionRouteGroupRequest], - typing.Union[ + Union[ transition_route_group.TransitionRouteGroup, - typing.Awaitable[transition_route_group.TransitionRouteGroup], + Awaitable[transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_transition_route_group( @property def create_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_transition_route_group.CreateTransitionRouteGroupRequest], - typing.Union[ + Union[ gcdc_transition_route_group.TransitionRouteGroup, - typing.Awaitable[gcdc_transition_route_group.TransitionRouteGroup], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_transition_route_group( @property def update_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_transition_route_group.UpdateTransitionRouteGroupRequest], - typing.Union[ + Union[ gcdc_transition_route_group.TransitionRouteGroup, - typing.Awaitable[gcdc_transition_route_group.TransitionRouteGroup], + Awaitable[gcdc_transition_route_group.TransitionRouteGroup], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_transition_route_group( @property def delete_transition_route_group( self, - ) -> typing.Callable[ + ) -> Callable[ [transition_route_group.DeleteTransitionRouteGroupRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py index baf9063f..eefe8323 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/transition_route_groups/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 @@ -30,8 +28,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,9 @@ def __init__( 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) @@ -119,70 +119,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,23 +170,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -214,7 +185,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -237,13 +208,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -382,7 +355,7 @@ def update_transition_route_group( def delete_transition_route_group( self, ) -> Callable[ - [transition_route_group.DeleteTransitionRouteGroupRequest], empty.Empty + [transition_route_group.DeleteTransitionRouteGroupRequest], empty_pb2.Empty ]: r"""Return a callable for the delete transition route group method over gRPC. @@ -405,7 +378,7 @@ def delete_transition_route_group( ] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup", request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_transition_route_group"] 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 cdf8347f..a9d6024d 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # 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 @@ -31,8 +29,7 @@ from google.cloud.dialogflowcx_v3beta1.types import ( transition_route_group as gcdc_transition_route_group, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import TransitionRouteGroupsTransport, DEFAULT_CLIENT_INFO from .grpc import TransitionRouteGroupsGrpcTransport @@ -58,7 +55,7 @@ class TransitionRouteGroupsGrpcAsyncIOTransport(TransitionRouteGroupsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,9 @@ def __init__( 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) @@ -164,70 +166,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,17 +216,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -387,7 +359,7 @@ def delete_transition_route_group( self, ) -> Callable[ [transition_route_group.DeleteTransitionRouteGroupRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete transition route group method over gRPC. @@ -410,7 +382,7 @@ def delete_transition_route_group( ] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroups/DeleteTransitionRouteGroup", request_serializer=transition_route_group.DeleteTransitionRouteGroupRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_transition_route_group"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py index 93418cef..586be181 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import VersionsClient from .async_client import VersionsAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py index 757c682d..0cde3c6d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -34,11 +32,10 @@ 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 -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport from .client import VersionsClient @@ -56,31 +53,27 @@ class VersionsAsyncClient: version_path = staticmethod(VersionsClient.version_path) parse_version_path = staticmethod(VersionsClient.parse_version_path) - common_billing_account_path = staticmethod( VersionsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( VersionsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(VersionsClient.common_folder_path) parse_common_folder_path = staticmethod(VersionsClient.parse_common_folder_path) - common_organization_path = staticmethod(VersionsClient.common_organization_path) parse_common_organization_path = staticmethod( VersionsClient.parse_common_organization_path ) - common_project_path = staticmethod(VersionsClient.common_project_path) parse_common_project_path = staticmethod(VersionsClient.parse_common_project_path) - common_location_path = staticmethod(VersionsClient.common_location_path) parse_common_location_path = staticmethod(VersionsClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: VersionsTransport: The transport used by the client instance. @@ -126,12 +119,12 @@ def transport(self) -> VersionsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, VersionsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = VersionsClient( credentials=credentials, transport=transport, @@ -196,7 +188,6 @@ async def list_versions( 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. @@ -226,7 +217,6 @@ async def list_versions( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -281,7 +271,6 @@ async def get_version( 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. @@ -306,7 +295,6 @@ async def get_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -364,7 +352,6 @@ async def create_version( This corresponds to the ``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. @@ -394,7 +381,6 @@ async def create_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if version is not None: @@ -433,7 +419,7 @@ async def update_version( request: gcdc_version.UpdateVersionRequest = None, *, version: gcdc_version.Version = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -458,7 +444,6 @@ async def update_version( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -483,7 +468,6 @@ async def update_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if version is not None: request.version = version if update_mask is not None: @@ -536,7 +520,6 @@ async def delete_version( 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. @@ -557,7 +540,6 @@ async def delete_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -589,7 +571,8 @@ async def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Loads a specified version to draft version. + r"""Loads resources in the specified version to the draft + flow. Args: request (:class:`google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest`): @@ -598,13 +581,12 @@ async def load_version( name (:class:`str`): Required. The [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - be loaded to draft version. Format: + be loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. 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. @@ -644,7 +626,6 @@ async def load_version( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -669,8 +650,8 @@ async def load_version( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py index 3628b96f..520833d0 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -38,11 +36,10 @@ 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 -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import VersionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import VersionsGrpcTransport from .transports.grpc_asyncio import VersionsGrpcAsyncIOTransport @@ -61,7 +58,7 @@ class VersionsClientMeta(type): _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -86,7 +83,8 @@ class VersionsClient(metaclass=VersionsClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -120,7 +118,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -137,7 +136,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -156,10 +155,11 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> VersionsTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - VersionsTransport: The transport used by the client instance. + VersionsTransport: The transport used by the client + instance. """ return self._transport @@ -167,14 +167,14 @@ def transport(self) -> VersionsTransport: def version_path( project: str, location: str, agent: str, flow: str, version: str, ) -> str: - """Return a fully-qualified version string.""" + """Returns a fully-qualified version string.""" return "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @staticmethod def parse_version_path(path: str) -> Dict[str, str]: - """Parse a version path into its component segments.""" + """Parses a version path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/flows/(?P.+?)/versions/(?P.+?)$", path, @@ -183,7 +183,7 @@ def parse_version_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -196,7 +196,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -207,7 +207,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -229,7 +229,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -243,12 +243,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, VersionsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the versions client. + """Instantiates the versions client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -303,9 +303,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -317,12 +318,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -337,8 +340,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -378,7 +381,6 @@ def list_versions( 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. @@ -410,10 +412,8 @@ def list_versions( # there are no flattened fields. if not isinstance(request, version.ListVersionsRequest): request = version.ListVersionsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -464,7 +464,6 @@ def get_version( 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. @@ -491,10 +490,8 @@ def get_version( # there are no flattened fields. if not isinstance(request, version.GetVersionRequest): request = version.GetVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -548,7 +545,6 @@ def create_version( This corresponds to the ``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. @@ -580,10 +576,8 @@ def create_version( # there are no flattened fields. if not isinstance(request, gcdc_version.CreateVersionRequest): request = gcdc_version.CreateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if version is not None: @@ -618,7 +612,7 @@ def update_version( request: gcdc_version.UpdateVersionRequest = None, *, version: gcdc_version.Version = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -643,7 +637,6 @@ def update_version( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -670,10 +663,8 @@ def update_version( # there are no flattened fields. if not isinstance(request, gcdc_version.UpdateVersionRequest): request = gcdc_version.UpdateVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if version is not None: request.version = version if update_mask is not None: @@ -722,7 +713,6 @@ def delete_version( 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. @@ -745,10 +735,8 @@ def delete_version( # there are no flattened fields. if not isinstance(request, version.DeleteVersionRequest): request = version.DeleteVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -776,7 +764,8 @@ def load_version( timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Loads a specified version to draft version. + r"""Loads resources in the specified version to the draft + flow. Args: request (google.cloud.dialogflowcx_v3beta1.types.LoadVersionRequest): @@ -785,13 +774,12 @@ def load_version( name (str): Required. The [Version][google.cloud.dialogflow.cx.v3beta1.Version] to - be loaded to draft version. Format: + be loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. 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. @@ -833,10 +821,8 @@ def load_version( # there are no flattened fields. if not isinstance(request, version.LoadVersionRequest): request = version.LoadVersionRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -857,8 +843,8 @@ def load_version( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, - metadata_type=struct.Struct, + empty_pb2.Empty, + metadata_type=struct_pb2.Struct, ) # Done; return the response. diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py index f12a3a14..345027c5 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py index aa4c96b0..c5a42a0e 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py index 731a8c23..32096dfa 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import version from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -41,6 +40,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class VersionsTransport(abc.ABC): """Abstract transport class for Versions.""" @@ -50,21 +60,24 @@ class VersionsTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -73,13 +86,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -87,28 +100,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -141,56 +201,53 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_versions( self, - ) -> typing.Callable[ + ) -> Callable[ [version.ListVersionsRequest], - typing.Union[ - version.ListVersionsResponse, typing.Awaitable[version.ListVersionsResponse] - ], + Union[version.ListVersionsResponse, Awaitable[version.ListVersionsResponse]], ]: raise NotImplementedError() @property def get_version( self, - ) -> typing.Callable[ - [version.GetVersionRequest], - typing.Union[version.Version, typing.Awaitable[version.Version]], + ) -> Callable[ + [version.GetVersionRequest], Union[version.Version, Awaitable[version.Version]] ]: raise NotImplementedError() @property def create_version( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_version.CreateVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_version( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_version.UpdateVersionRequest], - typing.Union[gcdc_version.Version, typing.Awaitable[gcdc_version.Version]], + Union[gcdc_version.Version, Awaitable[gcdc_version.Version]], ]: raise NotImplementedError() @property def delete_version( self, - ) -> typing.Callable[ + ) -> Callable[ [version.DeleteVersionRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def load_version( self, - ) -> typing.Callable[ + ) -> Callable[ [version.LoadVersionRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py index 7d5ba95d..9477f3f2 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import operations_v1 # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # 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 version from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -111,7 +109,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -119,70 +120,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -190,24 +171,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - self._operations_client = None - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -215,7 +186,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -238,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -323,7 +296,7 @@ def get_version(self) -> Callable[[version.GetVersionRequest], version.Version]: @property def create_version( self, - ) -> Callable[[gcdc_version.CreateVersionRequest], operations.Operation]: + ) -> Callable[[gcdc_version.CreateVersionRequest], operations_pb2.Operation]: r"""Return a callable for the create version method over gRPC. Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] @@ -344,7 +317,7 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion", request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @@ -376,7 +349,9 @@ def update_version( return self._stubs["update_version"] @property - def delete_version(self) -> Callable[[version.DeleteVersionRequest], empty.Empty]: + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], empty_pb2.Empty]: r"""Return a callable for the delete version method over gRPC. Deletes the specified @@ -396,17 +371,18 @@ def delete_version(self) -> Callable[[version.DeleteVersionRequest], empty.Empty self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/DeleteVersion", request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_version"] @property def load_version( self, - ) -> Callable[[version.LoadVersionRequest], operations.Operation]: + ) -> Callable[[version.LoadVersionRequest], operations_pb2.Operation]: r"""Return a callable for the load version method over gRPC. - Loads a specified version to draft version. + Loads resources in the specified version to the draft + flow. Returns: Callable[[~.LoadVersionRequest], @@ -422,7 +398,7 @@ def load_version( self._stubs["load_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion", request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["load_version"] 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 14c0f00c..d1a29c1c 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/versions/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,25 +13,23 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import version from google.cloud.dialogflowcx_v3beta1.types import version as gcdc_version -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import VersionsTransport, DEFAULT_CLIENT_INFO from .grpc import VersionsGrpcTransport @@ -58,7 +55,7 @@ class VersionsGrpcAsyncIOTransport(VersionsTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -66,7 +63,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -144,10 +144,10 @@ def __init__( 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 + 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: @@ -156,7 +156,10 @@ def __init__( 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] = {} + self._operations_client = None if api_mtls_endpoint: warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) @@ -164,70 +167,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -235,18 +217,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - self._operations_client = None + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -333,7 +305,9 @@ def get_version( @property def create_version( self, - ) -> Callable[[gcdc_version.CreateVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [gcdc_version.CreateVersionRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create version method over gRPC. Creates a [Version][google.cloud.dialogflow.cx.v3beta1.Version] @@ -354,7 +328,7 @@ def create_version( self._stubs["create_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/CreateVersion", request_serializer=gcdc_version.CreateVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_version"] @@ -388,7 +362,7 @@ def update_version( @property def delete_version( self, - ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty.Empty]]: + ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete version method over gRPC. Deletes the specified @@ -408,17 +382,18 @@ def delete_version( self._stubs["delete_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/DeleteVersion", request_serializer=version.DeleteVersionRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_version"] @property def load_version( self, - ) -> Callable[[version.LoadVersionRequest], Awaitable[operations.Operation]]: + ) -> Callable[[version.LoadVersionRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the load version method over gRPC. - Loads a specified version to draft version. + Loads resources in the specified version to the draft + flow. Returns: Callable[[~.LoadVersionRequest], @@ -434,7 +409,7 @@ def load_version( self._stubs["load_version"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Versions/LoadVersion", request_serializer=version.LoadVersionRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["load_version"] diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py index 2483e3be..28308a0b 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import WebhooksClient from .async_client import WebhooksAsyncClient diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py index 8c4dee0a..beb8b7b7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,18 +20,17 @@ import pkg_resources import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.dialogflowcx_v3beta1.services.webhooks import pagers from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport from .client import WebhooksClient @@ -49,33 +46,31 @@ class WebhooksAsyncClient: DEFAULT_ENDPOINT = WebhooksClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = WebhooksClient.DEFAULT_MTLS_ENDPOINT + service_path = staticmethod(WebhooksClient.service_path) + parse_service_path = staticmethod(WebhooksClient.parse_service_path) webhook_path = staticmethod(WebhooksClient.webhook_path) parse_webhook_path = staticmethod(WebhooksClient.parse_webhook_path) - common_billing_account_path = staticmethod( WebhooksClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( WebhooksClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(WebhooksClient.common_folder_path) parse_common_folder_path = staticmethod(WebhooksClient.parse_common_folder_path) - common_organization_path = staticmethod(WebhooksClient.common_organization_path) parse_common_organization_path = staticmethod( WebhooksClient.parse_common_organization_path ) - common_project_path = staticmethod(WebhooksClient.common_project_path) parse_common_project_path = staticmethod(WebhooksClient.parse_common_project_path) - common_location_path = staticmethod(WebhooksClient.common_location_path) parse_common_location_path = staticmethod(WebhooksClient.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. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -90,7 +85,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -107,7 +102,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> WebhooksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: WebhooksTransport: The transport used by the client instance. @@ -121,12 +116,12 @@ def transport(self) -> WebhooksTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, WebhooksTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the webhooks client. + """Instantiates the webhooks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -158,7 +153,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = WebhooksClient( credentials=credentials, transport=transport, @@ -189,7 +183,6 @@ async def list_webhooks( 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. @@ -219,7 +212,6 @@ async def list_webhooks( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -271,7 +263,6 @@ async def get_webhook( 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. @@ -303,7 +294,6 @@ async def get_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -355,7 +345,6 @@ async def create_webhook( This corresponds to the ``webhook`` 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. @@ -387,7 +376,6 @@ async def create_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if webhook is not None: @@ -418,7 +406,7 @@ async def update_webhook( request: gcdc_webhook.UpdateWebhookRequest = None, *, webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -442,7 +430,6 @@ async def update_webhook( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -474,7 +461,6 @@ async def update_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if webhook is not None: request.webhook = webhook if update_mask is not None: @@ -524,7 +510,6 @@ async def delete_webhook( 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. @@ -545,7 +530,6 @@ async def delete_webhook( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py index b12a948a..e68155e7 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions # type: ignore +from google.api_core import 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 # 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 @@ -35,9 +33,8 @@ 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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore - +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import WebhooksTransport, DEFAULT_CLIENT_INFO from .transports.grpc import WebhooksGrpcTransport from .transports.grpc_asyncio import WebhooksGrpcAsyncIOTransport @@ -56,7 +53,7 @@ class WebhooksClientMeta(type): _transport_registry["grpc_asyncio"] = WebhooksGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[WebhooksTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class WebhooksClient(metaclass=WebhooksClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS 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: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,23 +150,40 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> WebhooksTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - WebhooksTransport: The transport used by the client instance. + WebhooksTransport: The transport used by the client + instance. """ return self._transport + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def webhook_path(project: str, location: str, agent: str, webhook: str,) -> str: - """Return a fully-qualified webhook string.""" + """Returns a fully-qualified webhook string.""" return "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @staticmethod def parse_webhook_path(path: str) -> Dict[str, str]: - """Parse a webhook path into its component segments.""" + """Parses a webhook path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)/webhooks/(?P.+?)$", path, @@ -176,7 +192,7 @@ def parse_webhook_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -189,7 +205,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -200,7 +216,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -211,7 +227,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -222,7 +238,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -236,12 +252,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, WebhooksTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the webhooks client. + """Instantiates the webhooks client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -296,9 +312,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + 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: @@ -310,12 +327,14 @@ def __init__( elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) + 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" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -330,8 +349,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -369,7 +388,6 @@ def list_webhooks( 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. @@ -401,10 +419,8 @@ def list_webhooks( # there are no flattened fields. if not isinstance(request, webhook.ListWebhooksRequest): request = webhook.ListWebhooksRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -452,7 +468,6 @@ def get_webhook( 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. @@ -486,10 +501,8 @@ def get_webhook( # there are no flattened fields. if not isinstance(request, webhook.GetWebhookRequest): request = webhook.GetWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -537,7 +550,6 @@ def create_webhook( This corresponds to the ``webhook`` 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. @@ -571,10 +583,8 @@ def create_webhook( # there are no flattened fields. if not isinstance(request, gcdc_webhook.CreateWebhookRequest): request = gcdc_webhook.CreateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if webhook is not None: @@ -601,7 +611,7 @@ def update_webhook( request: gcdc_webhook.UpdateWebhookRequest = None, *, webhook: gcdc_webhook.Webhook = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -625,7 +635,6 @@ def update_webhook( This corresponds to the ``update_mask`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -659,10 +668,8 @@ def update_webhook( # there are no flattened fields. if not isinstance(request, gcdc_webhook.UpdateWebhookRequest): request = gcdc_webhook.UpdateWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if webhook is not None: request.webhook = webhook if update_mask is not None: @@ -708,7 +715,6 @@ def delete_webhook( 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. @@ -731,10 +737,8 @@ def delete_webhook( # there are no flattened fields. if not isinstance(request, webhook.DeleteWebhookRequest): request = webhook.DeleteWebhookRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py index 4dec3eb1..f11bff91 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py index de5771fe..17f318f9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py index 1da5195f..cb23b0a9 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +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 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -39,6 +38,17 @@ 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 + +_API_CORE_VERSION = google.api_core.__version__ + class WebhooksTransport(abc.ABC): """Abstract transport class for Webhooks.""" @@ -48,21 +58,24 @@ class WebhooksTransport(abc.ABC): "https://www.googleapis.com/auth/dialogflow", ) + DEFAULT_HOST: str = "dialogflow.googleapis.com" + def __init__( self, *, - host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, + 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, **kwargs, ) -> None: """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -71,13 +84,13 @@ def __init__( credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. + 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 + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. @@ -85,28 +98,75 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are 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 + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. @@ -131,47 +191,44 @@ def _prep_wrapped_messages(self, client_info): @property def list_webhooks( self, - ) -> typing.Callable[ + ) -> Callable[ [webhook.ListWebhooksRequest], - typing.Union[ - webhook.ListWebhooksResponse, typing.Awaitable[webhook.ListWebhooksResponse] - ], + Union[webhook.ListWebhooksResponse, Awaitable[webhook.ListWebhooksResponse]], ]: raise NotImplementedError() @property def get_webhook( self, - ) -> typing.Callable[ - [webhook.GetWebhookRequest], - typing.Union[webhook.Webhook, typing.Awaitable[webhook.Webhook]], + ) -> Callable[ + [webhook.GetWebhookRequest], Union[webhook.Webhook, Awaitable[webhook.Webhook]] ]: raise NotImplementedError() @property def create_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_webhook.CreateWebhookRequest], - typing.Union[gcdc_webhook.Webhook, typing.Awaitable[gcdc_webhook.Webhook]], + Union[gcdc_webhook.Webhook, Awaitable[gcdc_webhook.Webhook]], ]: raise NotImplementedError() @property def update_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [gcdc_webhook.UpdateWebhookRequest], - typing.Union[gcdc_webhook.Webhook, typing.Awaitable[gcdc_webhook.Webhook]], + Union[gcdc_webhook.Webhook, Awaitable[gcdc_webhook.Webhook]], ]: raise NotImplementedError() @property def delete_webhook( self, - ) -> typing.Callable[ + ) -> Callable[ [webhook.DeleteWebhookRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py index e661ac29..753d2d80 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple +from 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 -from google import auth # type: ignore -from google.auth import credentials # 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 webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import WebhooksTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -109,7 +107,9 @@ def __init__( 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) @@ -117,70 +117,50 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -188,23 +168,14 @@ def __init__( ], ) - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) + # 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: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -212,7 +183,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -235,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -355,7 +328,9 @@ def update_webhook( return self._stubs["update_webhook"] @property - def delete_webhook(self) -> Callable[[webhook.DeleteWebhookRequest], empty.Empty]: + def delete_webhook( + self, + ) -> Callable[[webhook.DeleteWebhookRequest], empty_pb2.Empty]: r"""Return a callable for the delete webhook method over gRPC. Deletes the specified webhook. @@ -374,7 +349,7 @@ def delete_webhook(self) -> Callable[[webhook.DeleteWebhookRequest], empty.Empty self._stubs["delete_webhook"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook", request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_webhook"] 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 75b7905f..2279f27d 100644 --- a/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py +++ b/google/cloud/dialogflowcx_v3beta1/services/webhooks/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple +from 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 import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.dialogflowcx_v3beta1.types import webhook from google.cloud.dialogflowcx_v3beta1.types import webhook as gcdc_webhook -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import WebhooksTransport, DEFAULT_CLIENT_INFO from .grpc import WebhooksGrpcTransport @@ -56,7 +53,7 @@ class WebhooksGrpcAsyncIOTransport(WebhooksTransport): def create_channel( cls, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -64,7 +61,7 @@ def create_channel( ) -> aio.Channel: """Create and return a gRPC AsyncIO channel object. Args: - address (Optional[str]): The host for the channel to use. + 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 @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "dialogflow.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -142,10 +142,10 @@ def __init__( 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 + 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: @@ -154,7 +154,9 @@ def __init__( 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) @@ -162,70 +164,49 @@ def __init__( warnings.warn("client_cert_source is deprecated", DeprecationWarning) if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. + # 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 - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - self._ssl_channel_credentials = ssl_credentials else: - host = host if ":" in host else host + ":443" + if 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 - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) + 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 + ) - 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, + ) - # create a new channel. The provided one is ignored. + if not self._grpc_channel: self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, + self._host, + credentials=self._credentials, credentials_file=credentials_file, + scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, options=[ ("grpc.max_send_message_length", -1), @@ -233,17 +214,8 @@ def __init__( ], ) - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: @@ -365,7 +337,7 @@ def update_webhook( @property def delete_webhook( self, - ) -> Callable[[webhook.DeleteWebhookRequest], Awaitable[empty.Empty]]: + ) -> Callable[[webhook.DeleteWebhookRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete webhook method over gRPC. Deletes the specified webhook. @@ -384,7 +356,7 @@ def delete_webhook( self._stubs["delete_webhook"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.cx.v3beta1.Webhooks/DeleteWebhook", request_serializer=webhook.DeleteWebhookRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_webhook"] diff --git a/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/google/cloud/dialogflowcx_v3beta1/types/__init__.py index 724959d2..00da5907 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .agent import ( Agent, AgentValidationResult, @@ -78,10 +76,14 @@ from .flow import ( CreateFlowRequest, DeleteFlowRequest, + ExportFlowRequest, + ExportFlowResponse, Flow, FlowValidationResult, GetFlowRequest, GetFlowValidationResultRequest, + ImportFlowRequest, + ImportFlowResponse, ListFlowsRequest, ListFlowsResponse, NluSettings, @@ -165,6 +167,7 @@ ExportTestCasesRequest, ExportTestCasesResponse, GetTestCaseRequest, + GetTestCaseResultRequest, ImportTestCasesMetadata, ImportTestCasesRequest, ImportTestCasesResponse, @@ -278,10 +281,14 @@ "VersionVariants", "CreateFlowRequest", "DeleteFlowRequest", + "ExportFlowRequest", + "ExportFlowResponse", "Flow", "FlowValidationResult", "GetFlowRequest", "GetFlowValidationResultRequest", + "ImportFlowRequest", + "ImportFlowResponse", "ListFlowsRequest", "ListFlowsResponse", "NluSettings", @@ -353,6 +360,7 @@ "ExportTestCasesRequest", "ExportTestCasesResponse", "GetTestCaseRequest", + "GetTestCaseResultRequest", "ImportTestCasesMetadata", "ImportTestCasesRequest", "ImportTestCasesResponse", diff --git a/google/cloud/dialogflowcx_v3beta1/types/agent.py b/google/cloud/dialogflowcx_v3beta1/types/agent.py index 174eace2..6dbf1caf 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/agent.py +++ b/google/cloud/dialogflowcx_v3beta1/types/agent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,14 +42,13 @@ class SpeechToTextSettings(proto.Message): r"""Settings related to speech recognition. - Attributes: enable_speech_adaptation (bool): Whether to use speech adaptation for speech recognition. """ - enable_speech_adaptation = proto.Field(proto.BOOL, number=1) + enable_speech_adaptation = proto.Field(proto.BOOL, number=1,) class Agent(proto.Message): @@ -88,6 +84,9 @@ class Agent(proto.Message): field cannot be set by the [Agents.UpdateAgent][google.cloud.dialogflow.cx.v3beta1.Agents.UpdateAgent] method. + supported_language_codes (Sequence[str]): + The list of all languages supported by the agent (except for + the ``default_language_code``). time_zone (str): Required. The time zone of the agent from the `time zone database `__, e.g., @@ -122,29 +121,20 @@ class Agent(proto.Message): enabled in detect intent requests. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - default_language_code = proto.Field(proto.STRING, number=3) - - time_zone = proto.Field(proto.STRING, number=5) - - description = proto.Field(proto.STRING, number=6) - - avatar_uri = proto.Field(proto.STRING, number=7) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + default_language_code = proto.Field(proto.STRING, number=3,) + supported_language_codes = proto.RepeatedField(proto.STRING, number=4,) + time_zone = proto.Field(proto.STRING, number=5,) + description = proto.Field(proto.STRING, number=6,) + avatar_uri = proto.Field(proto.STRING, number=7,) speech_to_text_settings = proto.Field( proto.MESSAGE, number=13, message="SpeechToTextSettings", ) - - start_flow = proto.Field(proto.STRING, number=16) - - security_settings = proto.Field(proto.STRING, number=17) - - enable_stackdriver_logging = proto.Field(proto.BOOL, number=18) - - enable_spell_correction = proto.Field(proto.BOOL, number=20) + start_flow = proto.Field(proto.STRING, number=16,) + security_settings = proto.Field(proto.STRING, number=17,) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=18,) + enable_spell_correction = proto.Field(proto.BOOL, number=20,) class ListAgentsRequest(proto.Message): @@ -163,11 +153,9 @@ class ListAgentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListAgentsResponse(proto.Message): @@ -189,8 +177,7 @@ def raw_page(self): return self agents = proto.RepeatedField(proto.MESSAGE, number=1, message="Agent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetAgentRequest(proto.Message): @@ -203,7 +190,7 @@ class GetAgentRequest(proto.Message): ``projects//locations//agents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateAgentRequest(proto.Message): @@ -218,8 +205,7 @@ class CreateAgentRequest(proto.Message): Required. The agent to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) agent = proto.Field(proto.MESSAGE, number=2, message="Agent",) @@ -237,8 +223,9 @@ class UpdateAgentRequest(proto.Message): """ agent = proto.Field(proto.MESSAGE, number=1, message="Agent",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteAgentRequest(proto.Message): @@ -251,7 +238,7 @@ class DeleteAgentRequest(proto.Message): ``projects//locations//agents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -268,11 +255,15 @@ class ExportAgentRequest(proto.Message): export the agent to. The format of this URI must be ``gs:///``. If left unspecified, the serialized agent is returned inline. + environment (str): + Optional. Environment name. If not set, draft environment is + assumed. Format: + ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) + environment = proto.Field(proto.STRING, number=5,) class ExportAgentResponse(proto.Message): @@ -288,9 +279,8 @@ class ExportAgentResponse(proto.Message): Uncompressed raw byte content for agent. """ - agent_uri = proto.Field(proto.STRING, number=1, oneof="agent") - - agent_content = proto.Field(proto.BYTES, number=2, oneof="agent") + agent_uri = proto.Field(proto.STRING, number=1, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=2, oneof="agent",) class RestoreAgentRequest(proto.Message): @@ -308,13 +298,20 @@ class RestoreAgentRequest(proto.Message): ``gs:///``. agent_content (bytes): Uncompressed raw byte content for agent. + restore_option (google.cloud.dialogflowcx_v3beta1.types.RestoreAgentRequest.RestoreOption): + Agent restore mode. If not specified, ``KEEP`` is assumed. """ - name = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2, oneof="agent") + class RestoreOption(proto.Enum): + r"""Restore option.""" + RESTORE_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 - agent_content = proto.Field(proto.BYTES, number=3, oneof="agent") + name = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2, oneof="agent",) + agent_content = proto.Field(proto.BYTES, number=3, oneof="agent",) + restore_option = proto.Field(proto.ENUM, number=5, enum=RestoreOption,) class ValidateAgentRequest(proto.Message): @@ -330,9 +327,8 @@ class ValidateAgentRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class GetAgentValidationResultRequest(proto.Message): @@ -348,9 +344,8 @@ class GetAgentValidationResultRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class AgentValidationResult(proto.Message): @@ -366,8 +361,7 @@ class AgentValidationResult(proto.Message): Contains all flow validation results. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) flow_validation_results = proto.RepeatedField( proto.MESSAGE, number=2, message=flow.FlowValidationResult, ) diff --git a/google/cloud/dialogflowcx_v3beta1/types/audio_config.py b/google/cloud/dialogflowcx_v3beta1/types/audio_config.py index df0a464f..f4132956 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/audio_config.py +++ b/google/cloud/dialogflowcx_v3beta1/types/audio_config.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -93,7 +90,6 @@ class OutputAudioEncoding(proto.Enum): class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -120,13 +116,10 @@ class SpeechWordInfo(proto.Message): also not rely on it to always be provided. """ - word = proto.Field(proto.STRING, number=3) - - start_offset = proto.Field(proto.MESSAGE, number=1, message=duration.Duration,) - - end_offset = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) - - confidence = proto.Field(proto.FLOAT, number=4) + word = proto.Field(proto.STRING, number=3,) + start_offset = proto.Field(proto.MESSAGE, number=1, message=duration_pb2.Duration,) + end_offset = proto.Field(proto.MESSAGE, number=2, message=duration_pb2.Duration,) + confidence = proto.Field(proto.FLOAT, number=4,) class InputAudioConfig(proto.Message): @@ -186,23 +179,16 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - - model = proto.Field(proto.STRING, number=7) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) + model = proto.Field(proto.STRING, number=7,) model_variant = proto.Field(proto.ENUM, number=10, enum="SpeechModelVariant",) - - single_utterance = proto.Field(proto.BOOL, number=8) + single_utterance = proto.Field(proto.BOOL, number=8,) class VoiceSelectionParams(proto.Message): r"""Description of which voice to use for speech synthesis. - Attributes: name (str): Optional. The name of the voice. If not set, the service @@ -224,14 +210,12 @@ class VoiceSelectionParams(proto.Message): gender rather than failing the request. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) ssml_gender = proto.Field(proto.ENUM, number=2, enum="SsmlVoiceGender",) class SynthesizeSpeechConfig(proto.Message): r"""Configuration of how speech should be synthesized. - Attributes: speaking_rate (float): Optional. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 @@ -265,14 +249,10 @@ class SynthesizeSpeechConfig(proto.Message): synthesized audio. """ - speaking_rate = proto.Field(proto.DOUBLE, number=1) - - pitch = proto.Field(proto.DOUBLE, number=2) - - volume_gain_db = proto.Field(proto.DOUBLE, number=3) - - effects_profile_id = proto.RepeatedField(proto.STRING, number=5) - + speaking_rate = proto.Field(proto.DOUBLE, number=1,) + pitch = proto.Field(proto.DOUBLE, number=2,) + volume_gain_db = proto.Field(proto.DOUBLE, number=3,) + effects_profile_id = proto.RepeatedField(proto.STRING, number=5,) voice = proto.Field(proto.MESSAGE, number=4, message="VoiceSelectionParams",) @@ -299,9 +279,7 @@ class OutputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="OutputAudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) synthesize_speech_config = proto.Field( proto.MESSAGE, number=3, message="SynthesizeSpeechConfig", ) diff --git a/google/cloud/dialogflowcx_v3beta1/types/entity_type.py b/google/cloud/dialogflowcx_v3beta1/types/entity_type.py index 7a940f3c..edfcb675 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/entity_type.py +++ b/google/cloud/dialogflowcx_v3beta1/types/entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -121,7 +118,6 @@ class AutoExpansionMode(proto.Enum): class Entity(proto.Message): r"""An **entity entry** for an associated entity type. - Attributes: value (str): Required. The primary value associated with this entity @@ -147,37 +143,28 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class ExcludedPhrase(proto.Message): r"""An excluded entity phrase that should not be matched. - Attributes: value (str): Required. The word or phrase to be excluded. """ - value = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) kind = proto.Field(proto.ENUM, number=3, enum=Kind,) - auto_expansion_mode = proto.Field(proto.ENUM, number=4, enum=AutoExpansionMode,) - entities = proto.RepeatedField(proto.MESSAGE, number=5, message=Entity,) - excluded_phrases = proto.RepeatedField( proto.MESSAGE, number=6, message=ExcludedPhrase, ) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) - - redact = proto.Field(proto.BOOL, number=9) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) + redact = proto.Field(proto.BOOL, number=9,) class ListEntityTypesRequest(proto.Message): @@ -209,13 +196,10 @@ class ListEntityTypesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListEntityTypesResponse(proto.Message): @@ -237,8 +221,7 @@ def raw_page(self): return self entity_types = proto.RepeatedField(proto.MESSAGE, number=1, message="EntityType",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEntityTypeRequest(proto.Message): @@ -264,9 +247,8 @@ class GetEntityTypeRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateEntityTypeRequest(proto.Message): @@ -293,11 +275,9 @@ class CreateEntityTypeRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type = proto.Field(proto.MESSAGE, number=2, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateEntityTypeRequest(proto.Message): @@ -324,10 +304,10 @@ class UpdateEntityTypeRequest(proto.Message): """ entity_type = proto.Field(proto.MESSAGE, number=1, message="EntityType",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteEntityTypeRequest(proto.Message): @@ -354,9 +334,8 @@ class DeleteEntityTypeRequest(proto.Message): of the entity type will be removed). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/environment.py b/google/cloud/dialogflowcx_v3beta1/types/environment.py index 60988fc9..f48c77a9 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/environment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/environment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -73,7 +70,6 @@ class Environment(proto.Message): class VersionConfig(proto.Message): r"""Configuration for the version. - Attributes: version (str): Required. Format: projects//flows//versions/. """ - version = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) + version = proto.Field(proto.STRING, number=1,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) version_configs = proto.RepeatedField( proto.MESSAGE, number=6, message=VersionConfig, ) - - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class ListEnvironmentsRequest(proto.Message): @@ -114,11 +106,9 @@ class ListEnvironmentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListEnvironmentsResponse(proto.Message): @@ -142,8 +132,7 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetEnvironmentRequest(proto.Message): @@ -158,7 +147,7 @@ class GetEnvironmentRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateEnvironmentRequest(proto.Message): @@ -177,8 +166,7 @@ class CreateEnvironmentRequest(proto.Message): Required. The environment to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) @@ -195,8 +183,9 @@ class UpdateEnvironmentRequest(proto.Message): """ environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteEnvironmentRequest(proto.Message): @@ -211,7 +200,7 @@ class DeleteEnvironmentRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class LookupEnvironmentHistoryRequest(proto.Message): @@ -231,11 +220,9 @@ class LookupEnvironmentHistoryRequest(proto.Message): request. """ - name = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class LookupEnvironmentHistoryResponse(proto.Message): @@ -258,8 +245,7 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/experiment.py b/google/cloud/dialogflowcx_v3beta1/types/experiment.py index 17d0d3b4..6f154764 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/experiment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/experiment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -43,7 +40,6 @@ class Experiment(proto.Message): r"""Represents an experiment in an environment. - Attributes: name (str): The name of the experiment. @@ -79,6 +75,10 @@ class Experiment(proto.Message): Last update time of this experiment. experiment_length (google.protobuf.duration_pb2.Duration): Maximum number of days to run the experiment. + If auto-rollout is not enabled, default value + and maximum will be 30 days. If auto-rollout is + enabled, default value and maximum will be 6 + days. variants_history (Sequence[google.cloud.dialogflowcx_v3beta1.types.VariantsHistory]): The history of updates to the experiment variants. @@ -93,7 +93,6 @@ class State(proto.Enum): class Definition(proto.Message): r"""Definition of the experiment. - Attributes: condition (str): The condition defines which subset of sessions are selected @@ -106,8 +105,7 @@ class Definition(proto.Message): experiment. """ - condition = proto.Field(proto.STRING, number=1) - + condition = proto.Field(proto.STRING, number=1,) version_variants = proto.Field( proto.MESSAGE, number=2, oneof="variants", message="VersionVariants", ) @@ -159,17 +157,13 @@ class ConfidenceInterval(proto.Message): Upper bound of the interval. """ - confidence_level = proto.Field(proto.DOUBLE, number=1) - - ratio = proto.Field(proto.DOUBLE, number=2) - - lower_bound = proto.Field(proto.DOUBLE, number=3) - - upper_bound = proto.Field(proto.DOUBLE, number=4) + confidence_level = proto.Field(proto.DOUBLE, number=1,) + ratio = proto.Field(proto.DOUBLE, number=2,) + lower_bound = proto.Field(proto.DOUBLE, number=3,) + upper_bound = proto.Field(proto.DOUBLE, number=4,) class Metric(proto.Message): r"""Metric and corresponding confidence intervals. - Attributes: type_ (google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.MetricType): Ratio-based metric type. Only one of type or count_type is @@ -189,28 +183,23 @@ class Metric(proto.Message): type_ = proto.Field( proto.ENUM, number=1, enum="Experiment.Result.MetricType", ) - count_type = proto.Field( proto.ENUM, number=5, enum="Experiment.Result.CountType", ) - - ratio = proto.Field(proto.DOUBLE, number=2, oneof="value") - - count = proto.Field(proto.DOUBLE, number=4, oneof="value") - + ratio = proto.Field(proto.DOUBLE, number=2, oneof="value",) + count = proto.Field(proto.DOUBLE, number=4, oneof="value",) confidence_interval = proto.Field( proto.MESSAGE, number=3, message="Experiment.Result.ConfidenceInterval", ) class VersionMetrics(proto.Message): r"""Version variant and associated metrics. - Attributes: version (str): The name of the flow [Version][google.cloud.dialogflow.cx.v3beta1.Version]. Format: - ``projects//locations//agents//flows//versions/``. + ``projects//locations//agents//flows//versions/``. metrics (Sequence[google.cloud.dialogflowcx_v3beta1.types.Experiment.Result.Metric]): The metrics and corresponding confidence intervals in the inference result. @@ -219,48 +208,34 @@ class VersionMetrics(proto.Message): this version. """ - version = proto.Field(proto.STRING, number=1) - + version = proto.Field(proto.STRING, number=1,) metrics = proto.RepeatedField( proto.MESSAGE, number=2, message="Experiment.Result.Metric", ) - - session_count = proto.Field(proto.INT32, number=3) + session_count = proto.Field(proto.INT32, number=3,) version_metrics = proto.RepeatedField( proto.MESSAGE, number=1, message="Experiment.Result.VersionMetrics", ) - last_update_time = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) state = proto.Field(proto.ENUM, number=4, enum=State,) - definition = proto.Field(proto.MESSAGE, number=5, message=Definition,) - result = proto.Field(proto.MESSAGE, number=6, message=Result,) - - create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp.Timestamp,) - - start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=8, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) last_update_time = proto.Field( - proto.MESSAGE, number=10, message=timestamp.Timestamp, + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, ) - experiment_length = proto.Field( - proto.MESSAGE, number=11, message=duration.Duration, + proto.MESSAGE, number=11, message=duration_pb2.Duration, ) - variants_history = proto.RepeatedField( proto.MESSAGE, number=12, message="VariantsHistory", ) @@ -268,7 +243,6 @@ class VersionMetrics(proto.Message): class VersionVariants(proto.Message): r"""A list of flow version variants. - Attributes: variants (Sequence[google.cloud.dialogflowcx_v3beta1.types.VersionVariants.Variant]): A list of flow version variants. @@ -276,7 +250,6 @@ class VersionVariants(proto.Message): class Variant(proto.Message): r"""A single flow version with specified traffic allocation. - Attributes: version (str): The name of the flow version. Format: @@ -289,18 +262,15 @@ class Variant(proto.Message): Whether the variant is for the control group. """ - version = proto.Field(proto.STRING, number=1) - - traffic_allocation = proto.Field(proto.FLOAT, number=2) - - is_control_group = proto.Field(proto.BOOL, number=3) + version = proto.Field(proto.STRING, number=1,) + traffic_allocation = proto.Field(proto.FLOAT, number=2,) + is_control_group = proto.Field(proto.BOOL, number=3,) variants = proto.RepeatedField(proto.MESSAGE, number=1, message=Variant,) class VariantsHistory(proto.Message): r"""The history of variants update. - Attributes: version_variants (google.cloud.dialogflowcx_v3beta1.types.VersionVariants): The flow versions as the variants. @@ -311,8 +281,7 @@ class VariantsHistory(proto.Message): version_variants = proto.Field( proto.MESSAGE, number=1, oneof="variants", message="VersionVariants", ) - - update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class ListExperimentsRequest(proto.Message): @@ -333,11 +302,9 @@ class ListExperimentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListExperimentsResponse(proto.Message): @@ -361,8 +328,7 @@ def raw_page(self): return self experiments = proto.RepeatedField(proto.MESSAGE, number=1, message="Experiment",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetExperimentRequest(proto.Message): @@ -377,7 +343,7 @@ class GetExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateExperimentRequest(proto.Message): @@ -396,8 +362,7 @@ class CreateExperimentRequest(proto.Message): Required. The experiment to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) experiment = proto.Field(proto.MESSAGE, number=2, message="Experiment",) @@ -414,8 +379,9 @@ class UpdateExperimentRequest(proto.Message): """ experiment = proto.Field(proto.MESSAGE, number=1, message="Experiment",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteExperimentRequest(proto.Message): @@ -430,7 +396,7 @@ class DeleteExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class StartExperimentRequest(proto.Message): @@ -443,7 +409,7 @@ class StartExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class StopExperimentRequest(proto.Message): @@ -456,7 +422,7 @@ class StopExperimentRequest(proto.Message): ``projects//locations//agents//environments//experiments/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/flow.py b/google/cloud/dialogflowcx_v3beta1/types/flow.py index 4e11e7ac..4e46dcfb 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/flow.py +++ b/google/cloud/dialogflowcx_v3beta1/types/flow.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import validation_message -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -39,13 +36,16 @@ "ValidateFlowRequest", "GetFlowValidationResultRequest", "FlowValidationResult", + "ImportFlowRequest", + "ImportFlowResponse", + "ExportFlowRequest", + "ExportFlowResponse", }, ) class NluSettings(proto.Message): r"""Settings related to NLU. - Attributes: model_type (google.cloud.dialogflowcx_v3beta1.types.NluSettings.ModelType): Indicates the type of NLU model. @@ -76,9 +76,7 @@ class ModelTrainingMode(proto.Enum): MODEL_TRAINING_MODE_MANUAL = 2 model_type = proto.Field(proto.ENUM, number=1, enum=ModelType,) - - classification_threshold = proto.Field(proto.FLOAT, number=3) - + classification_threshold = proto.Field(proto.FLOAT, number=3,) model_training_mode = proto.Field(proto.ENUM, number=4, enum=ModelTrainingMode,) @@ -146,24 +144,31 @@ class Flow(proto.Message): these handlers are evaluated on a first-match basis. The first one that matches the event get executed, with the rest being ignored. + transition_route_groups (Sequence[str]): + A flow's transition route group serve two purposes: + + - They are responsible for matching the user's first + utterances in the flow. + - They are inherited by every page's [transition route + groups][Page.transition_route_groups]. Transition route + groups defined in the page have higher priority than + those defined in the flow. + + Format:\ ``projects//locations//agents//flows//transitionRouteGroups/``. nlu_settings (google.cloud.dialogflowcx_v3beta1.types.NluSettings): NLU related settings of the flow. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=4, message=page.TransitionRoute, ) - event_handlers = proto.RepeatedField( proto.MESSAGE, number=10, message=page.EventHandler, ) - + transition_route_groups = proto.RepeatedField(proto.STRING, number=15,) nlu_settings = proto.Field(proto.MESSAGE, number=11, message="NluSettings",) @@ -181,7 +186,9 @@ class CreateFlowRequest(proto.Message): The language of the following fields in ``flow``: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -190,11 +197,9 @@ class CreateFlowRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) flow = proto.Field(proto.MESSAGE, number=2, message="Flow",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class DeleteFlowRequest(proto.Message): @@ -219,9 +224,8 @@ class DeleteFlowRequest(proto.Message): cleared). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class ListFlowsRequest(proto.Message): @@ -243,7 +247,9 @@ class ListFlowsRequest(proto.Message): language dependent: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -252,13 +258,10 @@ class ListFlowsRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - language_code = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + language_code = proto.Field(proto.STRING, number=4,) class ListFlowsResponse(proto.Message): @@ -280,8 +283,7 @@ def raw_page(self): return self flows = proto.RepeatedField(proto.MESSAGE, number=1, message="Flow",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetFlowRequest(proto.Message): @@ -297,7 +299,9 @@ class GetFlowRequest(proto.Message): are language dependent: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -306,9 +310,8 @@ class GetFlowRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class UpdateFlowRequest(proto.Message): @@ -325,7 +328,9 @@ class UpdateFlowRequest(proto.Message): The language of the following fields in ``flow``: - ``Flow.event_handlers.trigger_fulfillment.messages`` + - ``Flow.event_handlers.trigger_fulfillment.conditional_cases`` - ``Flow.transition_routes.trigger_fulfillment.messages`` + - ``Flow.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -335,10 +340,10 @@ class UpdateFlowRequest(proto.Message): """ flow = proto.Field(proto.MESSAGE, number=1, message="Flow",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - - language_code = proto.Field(proto.STRING, number=3) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field(proto.STRING, number=3,) class TrainFlowRequest(proto.Message): @@ -351,7 +356,7 @@ class TrainFlowRequest(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ValidateFlowRequest(proto.Message): @@ -367,9 +372,8 @@ class ValidateFlowRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class GetFlowValidationResultRequest(proto.Message): @@ -385,9 +389,8 @@ class GetFlowValidationResultRequest(proto.Message): language is used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class FlowValidationResult(proto.Message): @@ -404,13 +407,96 @@ class FlowValidationResult(proto.Message): Last time the flow was validated. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) validation_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=validation_message.ValidationMessage, ) + update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + + +class ImportFlowRequest(proto.Message): + r"""The request message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + Attributes: + parent (str): + Required. The agent to import the flow into. Format: + ``projects//locations//agents/``. + flow_uri (str): + The `Google Cloud + Storage `__ URI to + import flow from. The format of this URI must be + ``gs:///``. + flow_content (bytes): + Uncompressed raw byte content for flow. + import_option (google.cloud.dialogflowcx_v3beta1.types.ImportFlowRequest.ImportOption): + Flow import mode. If not specified, ``KEEP`` is assumed. + """ + + class ImportOption(proto.Enum): + r"""Import option.""" + IMPORT_OPTION_UNSPECIFIED = 0 + KEEP = 1 + FALLBACK = 2 + + parent = proto.Field(proto.STRING, number=1,) + flow_uri = proto.Field(proto.STRING, number=2, oneof="flow",) + flow_content = proto.Field(proto.BYTES, number=3, oneof="flow",) + import_option = proto.Field(proto.ENUM, number=4, enum=ImportOption,) + + +class ImportFlowResponse(proto.Message): + r"""The response message for + [Flows.ImportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ImportFlow]. + + Attributes: + flow (str): + The unique identifier of the new flow. Format: + ``projects//locations//agents//flows/``. + """ + + flow = proto.Field(proto.STRING, number=1,) + + +class ExportFlowRequest(proto.Message): + r"""The request message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + Attributes: + name (str): + Required. The name of the flow to export. Format: + ``projects//locations//agents//flows/``. + flow_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + export the flow to. The format of this URI must be + ``gs:///``. If left unspecified, + the serialized flow is returned inline. + include_referenced_flows (bool): + Optional. Whether to export flows referenced + by the specified flow. + """ + + name = proto.Field(proto.STRING, number=1,) + flow_uri = proto.Field(proto.STRING, number=2,) + include_referenced_flows = proto.Field(proto.BOOL, number=4,) + + +class ExportFlowResponse(proto.Message): + r"""The response message for + [Flows.ExportFlow][google.cloud.dialogflow.cx.v3beta1.Flows.ExportFlow]. + + 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]. + flow_content (bytes): + Uncompressed raw byte content for flow. + """ - update_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + flow_uri = proto.Field(proto.STRING, number=1, oneof="flow",) + flow_content = proto.Field(proto.BYTES, number=2, oneof="flow",) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py b/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py index 2f2a2323..e3da30ba 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py +++ b/google/cloud/dialogflowcx_v3beta1/types/fulfillment.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -68,7 +65,6 @@ class Fulfillment(proto.Message): class SetParameterAction(proto.Message): r"""Setting a parameter value. - Attributes: parameter (str): Display name of the parameter. @@ -77,9 +73,8 @@ class SetParameterAction(proto.Message): clears the parameter. """ - parameter = proto.Field(proto.STRING, number=1) - - value = proto.Field(proto.MESSAGE, number=2, message=struct.Value,) + parameter = proto.Field(proto.STRING, number=1,) + value = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Value,) class ConditionalCases(proto.Message): r"""A list of cascading if-else conditions. Cases are mutually @@ -126,7 +121,6 @@ class CaseContent(proto.Message): oneof="cases_or_message", message=response_message.ResponseMessage, ) - additional_cases = proto.Field( proto.MESSAGE, number=2, @@ -134,8 +128,7 @@ class CaseContent(proto.Message): message="Fulfillment.ConditionalCases", ) - condition = proto.Field(proto.STRING, number=1) - + condition = proto.Field(proto.STRING, number=1,) case_content = proto.RepeatedField( proto.MESSAGE, number=2, @@ -149,15 +142,11 @@ class CaseContent(proto.Message): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=response_message.ResponseMessage, ) - - webhook = proto.Field(proto.STRING, number=2) - - tag = proto.Field(proto.STRING, number=3) - + webhook = proto.Field(proto.STRING, number=2,) + tag = proto.Field(proto.STRING, number=3,) set_parameter_actions = proto.RepeatedField( proto.MESSAGE, number=4, message=SetParameterAction, ) - conditional_cases = proto.RepeatedField( proto.MESSAGE, number=5, message=ConditionalCases, ) diff --git a/google/cloud/dialogflowcx_v3beta1/types/intent.py b/google/cloud/dialogflowcx_v3beta1/types/intent.py index e68176a9..683e55cc 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/intent.py +++ b/google/cloud/dialogflowcx_v3beta1/types/intent.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -91,12 +88,12 @@ class Intent(proto.Message): assigned to fallback intents act as negative examples that triggers no-match event. labels (Sequence[google.cloud.dialogflowcx_v3beta1.types.Intent.LabelsEntry]): - Optional. The key/value metadata to label an intent. Labels - can contain lowercase letters, digits and the symbols '-' - and '_'. International characters are allowed, including - letters from unicase alphabets. Keys must start with a - letter. Keys and values can be no longer than 63 characters - and no more than 128 bytes. + The key/value metadata to label an intent. Labels can + contain lowercase letters, digits and the symbols '-' and + '_'. International characters are allowed, including letters + from unicase alphabets. Keys must start with a letter. Keys + and values can be no longer than 63 characters and no more + than 128 bytes. Prefix "sys-" is reserved for Dialogflow defined labels. Currently allowed Dialogflow defined labels include: @@ -106,10 +103,10 @@ class Intent(proto.Message): "sys-head" means the intent is a head intent. "sys-contextual" means the intent is a contextual intent. description (str): - Optional. Human readable description for - better understanding an intent like its scope, - content, result etc. Maximum character limit: - 140 characters. + Human readable description for better + understanding an intent like its scope, content, + result etc. Maximum character limit: 140 + characters. """ class TrainingPhrase(proto.Message): @@ -151,7 +148,6 @@ class TrainingPhrase(proto.Message): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -163,21 +159,17 @@ class Part(proto.Message): phrase. """ - text = proto.Field(proto.STRING, number=1) - - parameter_id = proto.Field(proto.STRING, number=2) - - id = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + parameter_id = proto.Field(proto.STRING, number=2,) + id = proto.Field(proto.STRING, number=1,) parts = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.TrainingPhrase.Part", ) - - repeat_count = proto.Field(proto.INT32, number=3) + repeat_count = proto.Field(proto.INT32, number=3,) class Parameter(proto.Message): r"""Represents an intent parameter. - Attributes: id (str): Required. The unique identifier of the parameter. This field @@ -206,31 +198,21 @@ class Parameter(proto.Message): is enabled. """ - id = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - is_list = proto.Field(proto.BOOL, number=3) - - redact = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + id = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + is_list = proto.Field(proto.BOOL, number=3,) + redact = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=3, message=TrainingPhrase, ) - parameters = proto.RepeatedField(proto.MESSAGE, number=4, message=Parameter,) - - priority = proto.Field(proto.INT32, number=5) - - is_fallback = proto.Field(proto.BOOL, number=6) - - labels = proto.MapField(proto.STRING, proto.STRING, number=7) - - description = proto.Field(proto.STRING, number=8) + priority = proto.Field(proto.INT32, number=5,) + is_fallback = proto.Field(proto.BOOL, number=6,) + labels = proto.MapField(proto.STRING, proto.STRING, number=7,) + description = proto.Field(proto.STRING, number=8,) class ListIntentsRequest(proto.Message): @@ -263,15 +245,11 @@ class ListIntentsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) intent_view = proto.Field(proto.ENUM, number=5, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListIntentsResponse(proto.Message): @@ -293,8 +271,7 @@ def raw_page(self): return self intents = proto.RepeatedField(proto.MESSAGE, number=1, message="Intent",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetIntentRequest(proto.Message): @@ -318,9 +295,8 @@ class GetIntentRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateIntentRequest(proto.Message): @@ -345,11 +321,9 @@ class CreateIntentRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intent = proto.Field(proto.MESSAGE, number=2, message="Intent",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateIntentRequest(proto.Message): @@ -376,10 +350,10 @@ class UpdateIntentRequest(proto.Message): """ intent = proto.Field(proto.MESSAGE, number=1, message="Intent",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeleteIntentRequest(proto.Message): @@ -392,7 +366,7 @@ class DeleteIntentRequest(proto.Message): ``projects//locations//agents//intents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/page.py b/google/cloud/dialogflowcx_v3beta1/types/page.py index 7fb8315a..1822aebd 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/page.py +++ b/google/cloud/dialogflowcx_v3beta1/types/page.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import fulfillment -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -122,22 +119,16 @@ class Page(proto.Message): input. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) entry_fulfillment = proto.Field( proto.MESSAGE, number=7, message=fulfillment.Fulfillment, ) - form = proto.Field(proto.MESSAGE, number=4, message="Form",) - - transition_route_groups = proto.RepeatedField(proto.STRING, number=11) - + transition_route_groups = proto.RepeatedField(proto.STRING, number=11,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=9, message="TransitionRoute", ) - event_handlers = proto.RepeatedField( proto.MESSAGE, number=10, message="EventHandler", ) @@ -159,7 +150,6 @@ class Form(proto.Message): class Parameter(proto.Message): r"""Represents a form parameter. - Attributes: display_name (str): Required. The human-readable name of the @@ -250,26 +240,19 @@ class FillBehavior(proto.Message): initial_prompt_fulfillment = proto.Field( proto.MESSAGE, number=3, message=fulfillment.Fulfillment, ) - reprompt_event_handlers = proto.RepeatedField( proto.MESSAGE, number=5, message="EventHandler", ) - display_name = proto.Field(proto.STRING, number=1) - - required = proto.Field(proto.BOOL, number=2) - - entity_type = proto.Field(proto.STRING, number=3) - - is_list = proto.Field(proto.BOOL, number=4) - + display_name = proto.Field(proto.STRING, number=1,) + required = proto.Field(proto.BOOL, number=2,) + entity_type = proto.Field(proto.STRING, number=3,) + is_list = proto.Field(proto.BOOL, number=4,) fill_behavior = proto.Field( proto.MESSAGE, number=7, message="Form.Parameter.FillBehavior", ) - - default_value = proto.Field(proto.MESSAGE, number=9, message=struct.Value,) - - redact = proto.Field(proto.BOOL, number=11) + default_value = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Value,) + redact = proto.Field(proto.BOOL, number=11,) parameters = proto.RepeatedField(proto.MESSAGE, number=1, message=Parameter,) @@ -312,17 +295,13 @@ class EventHandler(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=6) - - event = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=6,) + event = proto.Field(proto.STRING, number=4,) trigger_fulfillment = proto.Field( proto.MESSAGE, number=5, message=fulfillment.Fulfillment, ) - - target_page = proto.Field(proto.STRING, number=2, oneof="target") - - target_flow = proto.Field(proto.STRING, number=3, oneof="target") + target_page = proto.Field(proto.STRING, number=2, oneof="target",) + target_flow = proto.Field(proto.STRING, number=3, oneof="target",) class TransitionRoute(proto.Message): @@ -382,19 +361,14 @@ class TransitionRoute(proto.Message): ``projects//locations//agents//flows/``. """ - name = proto.Field(proto.STRING, number=6) - - intent = proto.Field(proto.STRING, number=1) - - condition = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=6,) + intent = proto.Field(proto.STRING, number=1,) + condition = proto.Field(proto.STRING, number=2,) trigger_fulfillment = proto.Field( proto.MESSAGE, number=3, message=fulfillment.Fulfillment, ) - - target_page = proto.Field(proto.STRING, number=4, oneof="target") - - target_flow = proto.Field(proto.STRING, number=5, oneof="target") + target_page = proto.Field(proto.STRING, number=4, oneof="target",) + target_flow = proto.Field(proto.STRING, number=5, oneof="target",) class ListPagesRequest(proto.Message): @@ -410,12 +384,21 @@ class ListPagesRequest(proto.Message): language dependent: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -430,13 +413,10 @@ class ListPagesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListPagesResponse(proto.Message): @@ -458,8 +438,7 @@ def raw_page(self): return self pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetPageRequest(proto.Message): @@ -475,12 +454,21 @@ class GetPageRequest(proto.Message): are language dependent: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -489,9 +477,8 @@ class GetPageRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreatePageRequest(proto.Message): @@ -508,12 +495,21 @@ class CreatePageRequest(proto.Message): The language of the following fields in ``page``: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -522,11 +518,9 @@ class CreatePageRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) page = proto.Field(proto.MESSAGE, number=2, message="Page",) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdatePageRequest(proto.Message): @@ -540,12 +534,21 @@ class UpdatePageRequest(proto.Message): The language of the following fields in ``page``: - ``Page.entry_fulfillment.messages`` + - ``Page.entry_fulfillment.conditional_cases`` + - ``Page.event_handlers.trigger_fulfillment.messages`` + - ``Page.event_handlers.trigger_fulfillment.conditional_cases`` - ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`` + - + + ``Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`` + - ``Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`` - - ``Page.transition_routes.trigger_fulfillment.messages`` - - ``Page.transition_route_groups.transition_routes.trigger_fulfillment.messages`` + ``Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`` + + - ``Page.transition_routes.trigger_fulfillment.messages`` + - ``Page.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -559,10 +562,10 @@ class UpdatePageRequest(proto.Message): """ page = proto.Field(proto.MESSAGE, number=1, message="Page",) - - language_code = proto.Field(proto.STRING, number=2) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=2,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class DeletePageRequest(proto.Message): @@ -587,9 +590,8 @@ class DeletePageRequest(proto.Message): cleared). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/response_message.py b/google/cloud/dialogflowcx_v3beta1/types/response_message.py index 6bdc8cae..96e6fd69 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/response_message.py +++ b/google/cloud/dialogflowcx_v3beta1/types/response_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -89,7 +86,6 @@ class ResponseMessage(proto.Message): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Required. A collection of text responses. @@ -100,9 +96,8 @@ class Text(proto.Message): Dialogflow request. """ - text = proto.RepeatedField(proto.STRING, number=1) - - allow_playback_interruption = proto.Field(proto.BOOL, number=2) + text = proto.RepeatedField(proto.STRING, number=1,) + allow_playback_interruption = proto.Field(proto.BOOL, number=2,) class LiveAgentHandoff(proto.Message): r"""Indicates that the conversation should be handed off to a live @@ -128,7 +123,7 @@ class LiveAgentHandoff(proto.Message): Dialogflow doesn't impose any structure on this. """ - metadata = proto.Field(proto.MESSAGE, number=1, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=1, message=struct_pb2.Struct,) class ConversationSuccess(proto.Message): r"""Indicates that the conversation succeeded, i.e., the bot handled the @@ -156,7 +151,7 @@ class ConversationSuccess(proto.Message): any structure on this. """ - metadata = proto.Field(proto.MESSAGE, number=1, message=struct.Struct,) + metadata = proto.Field(proto.MESSAGE, number=1, message=struct_pb2.Struct,) class OutputAudioText(proto.Message): r"""A text or ssml response that is preferentially used for TTS @@ -176,17 +171,15 @@ class OutputAudioText(proto.Message): Dialogflow request. """ - text = proto.Field(proto.STRING, number=1, oneof="source") - - ssml = proto.Field(proto.STRING, number=2, oneof="source") - - allow_playback_interruption = proto.Field(proto.BOOL, number=3) + text = proto.Field(proto.STRING, number=1, oneof="source",) + ssml = proto.Field(proto.STRING, number=2, oneof="source",) + allow_playback_interruption = proto.Field(proto.BOOL, number=3,) class EndInteraction(proto.Message): r"""Indicates that interaction with the Dialogflow agent has ended. This message is generated by Dialogflow only and not supposed to be defined by the user. - """ + """ class PlayAudio(proto.Message): r"""Specifies an audio clip to be played by the client as part of @@ -204,9 +197,8 @@ class PlayAudio(proto.Message): Dialogflow request. """ - audio_uri = proto.Field(proto.STRING, number=1) - - allow_playback_interruption = proto.Field(proto.BOOL, number=2) + audio_uri = proto.Field(proto.STRING, number=1,) + allow_playback_interruption = proto.Field(proto.BOOL, number=2,) class MixedAudio(proto.Message): r"""Represents an audio message that is composed of both segments @@ -224,7 +216,6 @@ class MixedAudio(proto.Message): class Segment(proto.Message): r"""Represents one segment of audio. - Attributes: audio (bytes): Raw audio synthesized from the Dialogflow @@ -241,42 +232,33 @@ class Segment(proto.Message): Dialogflow request. """ - audio = proto.Field(proto.BYTES, number=1, oneof="content") - - uri = proto.Field(proto.STRING, number=2, oneof="content") - - allow_playback_interruption = proto.Field(proto.BOOL, number=3) + audio = proto.Field(proto.BYTES, number=1, oneof="content",) + uri = proto.Field(proto.STRING, number=2, oneof="content",) + allow_playback_interruption = proto.Field(proto.BOOL, number=3,) segments = proto.RepeatedField( proto.MESSAGE, number=1, message="ResponseMessage.MixedAudio.Segment", ) text = proto.Field(proto.MESSAGE, number=1, oneof="message", message=Text,) - payload = proto.Field( - proto.MESSAGE, number=2, oneof="message", message=struct.Struct, + proto.MESSAGE, number=2, oneof="message", message=struct_pb2.Struct, ) - conversation_success = proto.Field( proto.MESSAGE, number=9, oneof="message", message=ConversationSuccess, ) - output_audio_text = proto.Field( proto.MESSAGE, number=8, oneof="message", message=OutputAudioText, ) - live_agent_handoff = proto.Field( proto.MESSAGE, number=10, oneof="message", message=LiveAgentHandoff, ) - end_interaction = proto.Field( proto.MESSAGE, number=11, oneof="message", message=EndInteraction, ) - play_audio = proto.Field( proto.MESSAGE, number=12, oneof="message", message=PlayAudio, ) - mixed_audio = proto.Field( proto.MESSAGE, number=13, oneof="message", message=MixedAudio, ) diff --git a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py index 2a991f64..59139f23 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/security_settings.py +++ b/google/cloud/dialogflowcx_v3beta1/types/security_settings.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,7 +42,7 @@ class GetSecuritySettingsRequest(proto.Message): ``projects//locations//securitySettings/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateSecuritySettingsRequest(proto.Message): @@ -65,13 +62,13 @@ class UpdateSecuritySettingsRequest(proto.Message): security_settings = proto.Field( proto.MESSAGE, number=1, message="SecuritySettings", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class ListSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.ListSecuritySettings][]. - Attributes: parent (str): Required. The location to list all security settings for. @@ -84,16 +81,13 @@ class ListSecuritySettingsRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSecuritySettingsResponse(proto.Message): r"""The response message for [SecuritySettings.ListSecuritySettings][]. - Attributes: security_settings (Sequence[google.cloud.dialogflowcx_v3beta1.types.SecuritySettings]): The list of security settings. @@ -110,13 +104,11 @@ def raw_page(self): security_settings = proto.RepeatedField( proto.MESSAGE, number=1, message="SecuritySettings", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.CreateSecuritySettings][]. - Attributes: parent (str): Required. The location to create an @@ -127,8 +119,7 @@ class CreateSecuritySettingsRequest(proto.Message): Required. The security settings to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) security_settings = proto.Field( proto.MESSAGE, number=2, message="SecuritySettings", ) @@ -136,7 +127,6 @@ class CreateSecuritySettingsRequest(proto.Message): class DeleteSecuritySettingsRequest(proto.Message): r"""The request message for [SecuritySettings.DeleteSecuritySettings][]. - Attributes: name (str): Required. The name of the @@ -145,7 +135,7 @@ class DeleteSecuritySettingsRequest(proto.Message): ``projects//locations//securitySettings/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class SecuritySettings(proto.Message): @@ -205,18 +195,12 @@ class PurgeDataType(proto.Enum): PURGE_DATA_TYPE_UNSPECIFIED = 0 DIALOGFLOW_HISTORY = 1 - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) redaction_strategy = proto.Field(proto.ENUM, number=3, enum=RedactionStrategy,) - redaction_scope = proto.Field(proto.ENUM, number=4, enum=RedactionScope,) - - inspect_template = proto.Field(proto.STRING, number=9) - - retention_window_days = proto.Field(proto.INT32, number=6, oneof="data_retention") - + inspect_template = proto.Field(proto.STRING, number=9,) + retention_window_days = proto.Field(proto.INT32, number=6, oneof="data_retention",) purge_data_types = proto.RepeatedField(proto.ENUM, number=8, enum=PurgeDataType,) diff --git a/google/cloud/dialogflowcx_v3beta1/types/session.py b/google/cloud/dialogflowcx_v3beta1/types/session.py index 411fe8ee..19b15006 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/session.py +++ b/google/cloud/dialogflowcx_v3beta1/types/session.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import audio_config from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent from google.cloud.dialogflowcx_v3beta1.types import page from google.cloud.dialogflowcx_v3beta1.types import response_message from google.cloud.dialogflowcx_v3beta1.types import session_entity_type -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.rpc import status_pb2 as status # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -57,7 +54,6 @@ class DetectIntentRequest(proto.Message): r"""The request to detect user's intent. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -86,12 +82,9 @@ class DetectIntentRequest(proto.Message): generate the output audio. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -99,7 +92,6 @@ class DetectIntentRequest(proto.Message): class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): Output only. The unique identifier of the @@ -126,12 +118,9 @@ class DetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - - output_audio = proto.Field(proto.BYTES, number=4) - + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) @@ -202,12 +191,9 @@ class StreamingDetectIntentRequest(proto.Message): generate the output audio. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) - output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -225,7 +211,13 @@ class StreamingDetectIntentResponse(proto.Message): what the user said. The last ``recognition_result`` has ``is_final`` set to ``true``. - 2. The last message contains ``detect_intent_response``. + 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``. Attributes: recognition_result (google.cloud.dialogflowcx_v3beta1.types.StreamingRecognitionResult): @@ -237,7 +229,6 @@ class StreamingDetectIntentResponse(proto.Message): recognition_result = proto.Field( proto.MESSAGE, number=1, oneof="response", message="StreamingRecognitionResult", ) - detect_intent_response = proto.Field( proto.MESSAGE, number=2, oneof="response", message="DetectIntentResponse", ) @@ -328,25 +319,20 @@ class MessageType(proto.Enum): END_OF_SINGLE_UTTERANCE = 2 message_type = proto.Field(proto.ENUM, number=1, enum=MessageType,) - - transcript = proto.Field(proto.STRING, number=2) - - is_final = proto.Field(proto.BOOL, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - stability = proto.Field(proto.FLOAT, number=6) - + transcript = proto.Field(proto.STRING, number=2,) + is_final = proto.Field(proto.BOOL, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + stability = proto.Field(proto.FLOAT, number=6,) speech_word_info = proto.RepeatedField( proto.MESSAGE, number=7, message=audio_config.SpeechWordInfo, ) - - speech_end_offset = proto.Field(proto.MESSAGE, number=8, message=duration.Duration,) + speech_end_offset = proto.Field( + proto.MESSAGE, number=8, message=duration_pb2.Duration, + ) class QueryParameters(proto.Message): r"""Represents the parameters of a conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -362,9 +348,20 @@ class QueryParameters(proto.Message): synonyms apply to all languages and persist for the session of this query. payload (google.protobuf.struct_pb2.Struct): - This field can be used to pass custom data - into the webhook associated with the agent. - Arbitrary JSON objects are supported. + This field can be used to pass custom data into the webhook + associated with the agent. Arbitrary JSON objects are + supported. Some integrations that query a Dialogflow agent + may provide additional information in the payload. In + particular, for the Dialogflow Phone Gateway integration, + this field has the form: + + :: + + { + "telephony": { + "caller_id": "+18558363987" + } + } parameters (google.protobuf.struct_pb2.Struct): Additional parameters to be put into [session parameters][SessionInfo.parameters]. To remove a parameter @@ -390,6 +387,22 @@ class QueryParameters(proto.Message): from composite entity property names to property values - Else: parameter value + current_page (str): + The unique identifier of the + [page][google.cloud.dialogflow.cx.v3beta1.Page] to override + the [current page][QueryResult.current_page] in the session. + Format: + ``projects//locations//agents//pages/``. + + If ``current_page`` is specified, the previous state of the + session will be ignored by Dialogflow, including the + [previous page][QueryResult.current_page] and the [previous + session parameters][QueryResult.parameters]. In most cases, + [current_page][google.cloud.dialogflow.cx.v3beta1.QueryParameters.current_page] + and + [parameters][google.cloud.dialogflow.cx.v3beta1.QueryParameters.parameters] + should be configured together to direct a session to a + specific state. disable_webhook (bool): Whether to disable webhook calls for this request. @@ -412,23 +425,17 @@ class QueryParameters(proto.Message): None-Match", "X-Forwarded-For", etc. """ - time_zone = proto.Field(proto.STRING, number=1) - - geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) - + time_zone = proto.Field(proto.STRING, number=1,) + geo_location = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=3, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - parameters = proto.Field(proto.MESSAGE, number=5, message=struct.Struct,) - - disable_webhook = proto.Field(proto.BOOL, number=7) - - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=8) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=10) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + parameters = proto.Field(proto.MESSAGE, number=5, message=struct_pb2.Struct,) + current_page = proto.Field(proto.STRING, number=6,) + disable_webhook = proto.Field(proto.BOOL, number=7,) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=8,) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=10,) class QueryInput(proto.Message): @@ -461,21 +468,15 @@ class QueryInput(proto.Message): """ text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - intent = proto.Field(proto.MESSAGE, number=3, oneof="input", message="IntentInput",) - audio = proto.Field(proto.MESSAGE, number=5, oneof="input", message="AudioInput",) - event = proto.Field(proto.MESSAGE, number=6, oneof="input", message="EventInput",) - dtmf = proto.Field(proto.MESSAGE, number=7, oneof="input", message="DtmfInput",) - - language_code = proto.Field(proto.STRING, number=4) + language_code = proto.Field(proto.STRING, number=4,) class QueryResult(proto.Message): r"""Represents the result of a conversational query. - Attributes: text (str): If [natural language @@ -486,12 +487,13 @@ class QueryResult(proto.Message): If an [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was provided as input, this field will contain a copy of the - intent identifier. + intent identifier. Format: + ``projects//locations//agents//intents/``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was - provided as input, this field will contain the trascript for - the audio. + provided as input, this field will contain the transcript + for the audio. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] was provided as input, this field will contain the name of @@ -575,40 +577,26 @@ class QueryResult(proto.Message): specified in the request. """ - text = proto.Field(proto.STRING, number=1, oneof="query") - - trigger_intent = proto.Field(proto.STRING, number=11, oneof="query") - - transcript = proto.Field(proto.STRING, number=12, oneof="query") - - trigger_event = proto.Field(proto.STRING, number=14, oneof="query") - - language_code = proto.Field(proto.STRING, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) - + text = proto.Field(proto.STRING, number=1, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=11, oneof="query",) + transcript = proto.Field(proto.STRING, number=12, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=14, oneof="query",) + language_code = proto.Field(proto.STRING, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) response_messages = proto.RepeatedField( proto.MESSAGE, number=4, message=response_message.ResponseMessage, ) - webhook_statuses = proto.RepeatedField( - proto.MESSAGE, number=13, message=status.Status, + proto.MESSAGE, number=13, message=status_pb2.Status, ) - webhook_payloads = proto.RepeatedField( - proto.MESSAGE, number=6, message=struct.Struct, + proto.MESSAGE, number=6, message=struct_pb2.Struct, ) - current_page = proto.Field(proto.MESSAGE, number=7, message=page.Page,) - intent = proto.Field(proto.MESSAGE, number=8, message=gcdc_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=9) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=9,) match = proto.Field(proto.MESSAGE, number=15, message="Match",) - - diagnostic_info = proto.Field(proto.MESSAGE, number=10, message=struct.Struct,) - + diagnostic_info = proto.Field(proto.MESSAGE, number=10, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) @@ -616,7 +604,6 @@ class QueryResult(proto.Message): class TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -624,7 +611,7 @@ class TextInput(proto.Message): exceed 256 characters. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) class IntentInput(proto.Message): @@ -637,12 +624,11 @@ class IntentInput(proto.Message): ``projects//locations//agents//intents/``. """ - intent = proto.Field(proto.STRING, number=1) + intent = proto.Field(proto.STRING, number=1,) class AudioInput(proto.Message): r"""Represents the natural speech audio to be processed. - Attributes: config (google.cloud.dialogflowcx_v3beta1.types.InputAudioConfig): Required. Instructs the speech recognizer how @@ -663,24 +649,21 @@ class AudioInput(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.InputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class EventInput(proto.Message): r"""Represents the event to trigger. - Attributes: event (str): Name of the event. """ - event = proto.Field(proto.STRING, number=1) + event = proto.Field(proto.STRING, number=1,) class DtmfInput(proto.Message): r"""Represents the input for dtmf event. - Attributes: digits (str): The dtmf digits. @@ -688,14 +671,12 @@ class DtmfInput(proto.Message): The finish digit (if any). """ - digits = proto.Field(proto.STRING, number=1) - - finish_digit = proto.Field(proto.STRING, number=2) + digits = proto.Field(proto.STRING, number=1,) + finish_digit = proto.Field(proto.STRING, number=2,) class Match(proto.Message): r"""Represents one match result of [MatchIntent][]. - Attributes: intent (google.cloud.dialogflowcx_v3beta1.types.Intent): The [Intent][google.cloud.dialogflow.cx.v3beta1.Intent] that @@ -759,21 +740,15 @@ class MatchType(proto.Enum): EVENT = 6 intent = proto.Field(proto.MESSAGE, number=1, message=gcdc_intent.Intent,) - - event = proto.Field(proto.STRING, number=6) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - resolved_input = proto.Field(proto.STRING, number=3) - + event = proto.Field(proto.STRING, number=6,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + resolved_input = proto.Field(proto.STRING, number=3,) match_type = proto.Field(proto.ENUM, number=4, enum=MatchType,) - - confidence = proto.Field(proto.FLOAT, number=5) + confidence = proto.Field(proto.FLOAT, number=5,) class MatchIntentRequest(proto.Message): r"""Request of [MatchIntent][]. - Attributes: session (str): Required. The name of the session this query is sent to. @@ -795,16 +770,13 @@ class MatchIntentRequest(proto.Message): Required. The input specification. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) query_params = proto.Field(proto.MESSAGE, number=2, message="QueryParameters",) - query_input = proto.Field(proto.MESSAGE, number=3, message="QueryInput",) class MatchIntentResponse(proto.Message): r"""Response of [MatchIntent][]. - Attributes: text (str): If [natural language @@ -815,12 +787,13 @@ class MatchIntentResponse(proto.Message): If an [intent][google.cloud.dialogflow.cx.v3beta1.IntentInput] was provided as input, this field will contain a copy of the - intent identifier. + intent identifier. Format: + ``projects//locations//agents//intents/``. transcript (str): If [natural language speech audio][google.cloud.dialogflow.cx.v3beta1.AudioInput] was - provided as input, this field will contain the trascript for - the audio. + provided as input, this field will contain the transcript + for the audio. trigger_event (str): If an [event][google.cloud.dialogflow.cx.v3beta1.EventInput] was provided as input, this field will contain a copy of the @@ -835,22 +808,16 @@ class MatchIntentResponse(proto.Message): but not limited to ``name`` and ``display_name``. """ - text = proto.Field(proto.STRING, number=1, oneof="query") - - trigger_intent = proto.Field(proto.STRING, number=2, oneof="query") - - transcript = proto.Field(proto.STRING, number=3, oneof="query") - - trigger_event = proto.Field(proto.STRING, number=6, oneof="query") - + text = proto.Field(proto.STRING, number=1, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=2, oneof="query",) + transcript = proto.Field(proto.STRING, number=3, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=6, oneof="query",) matches = proto.RepeatedField(proto.MESSAGE, number=4, message="Match",) - current_page = proto.Field(proto.MESSAGE, number=5, message=page.Page,) class FulfillIntentRequest(proto.Message): r"""Request of [FulfillIntent][] - Attributes: match_intent_request (google.cloud.dialogflowcx_v3beta1.types.MatchIntentRequest): Must be same as the corresponding MatchIntent @@ -865,9 +832,7 @@ class FulfillIntentRequest(proto.Message): match_intent_request = proto.Field( proto.MESSAGE, number=1, message="MatchIntentRequest", ) - match = proto.Field(proto.MESSAGE, number=2, message="Match",) - output_audio_config = proto.Field( proto.MESSAGE, number=3, message=audio_config.OutputAudioConfig, ) @@ -875,7 +840,6 @@ class FulfillIntentRequest(proto.Message): class FulfillIntentResponse(proto.Message): r"""Response of [FulfillIntent][] - Attributes: response_id (str): Output only. The unique identifier of the @@ -902,12 +866,9 @@ class FulfillIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field(proto.MESSAGE, number=2, message="QueryResult",) - - output_audio = proto.Field(proto.BYTES, number=3) - + output_audio = proto.Field(proto.BYTES, number=3,) output_audio_config = proto.Field( proto.MESSAGE, number=4, message=audio_config.OutputAudioConfig, ) @@ -929,9 +890,8 @@ class SentimentAnalysisResult(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py b/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py index 479d330b..3d0ce711 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py +++ b/google/cloud/dialogflowcx_v3beta1/types/session_entity_type.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import entity_type -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -77,10 +74,8 @@ class EntityOverrideMode(proto.Enum): ENTITY_OVERRIDE_MODE_OVERRIDE = 1 ENTITY_OVERRIDE_MODE_SUPPLEMENT = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) entity_override_mode = proto.Field(proto.ENUM, number=3, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=4, message=entity_type.EntityType.Entity, ) @@ -107,11 +102,9 @@ class ListSessionEntityTypesRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListSessionEntityTypesResponse(proto.Message): @@ -136,8 +129,7 @@ def raw_page(self): session_entity_types = proto.RepeatedField( proto.MESSAGE, number=1, message="SessionEntityType", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetSessionEntityTypeRequest(proto.Message): @@ -154,7 +146,7 @@ class GetSessionEntityTypeRequest(proto.Message): 'draft' environment. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -174,8 +166,7 @@ class CreateSessionEntityTypeRequest(proto.Message): Required. The session entity type to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) session_entity_type = proto.Field( proto.MESSAGE, number=2, message="SessionEntityType", ) @@ -200,8 +191,9 @@ class UpdateSessionEntityTypeRequest(proto.Message): session_entity_type = proto.Field( proto.MESSAGE, number=1, message="SessionEntityType", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteSessionEntityTypeRequest(proto.Message): @@ -219,7 +211,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): 'draft' environment. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/test_case.py b/google/cloud/dialogflowcx_v3beta1/types/test_case.py index 7620f9f0..06b6bde2 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/test_case.py +++ b/google/cloud/dialogflowcx_v3beta1/types/test_case.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import flow as gcdc_flow from google.cloud.dialogflowcx_v3beta1.types import intent as gcdc_intent from google.cloud.dialogflowcx_v3beta1.types import page as gcdc_page from google.cloud.dialogflowcx_v3beta1.types import response_message from google.cloud.dialogflowcx_v3beta1.types import session from google.cloud.dialogflowcx_v3beta1.types import transition_route_group -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as gr_status # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -66,6 +63,7 @@ "ExportTestCasesMetadata", "ListTestCaseResultsRequest", "ListTestCaseResultsResponse", + "GetTestCaseResultRequest", }, ) @@ -79,7 +77,6 @@ class TestResult(proto.Enum): class TestCase(proto.Message): r"""Represents a test case. - Attributes: name (str): The unique identifier of the test case. @@ -112,22 +109,17 @@ class TestCase(proto.Message): The latest test result. """ - name = proto.Field(proto.STRING, number=1) - - tags = proto.RepeatedField(proto.STRING, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - notes = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + tags = proto.RepeatedField(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + notes = proto.Field(proto.STRING, number=4,) test_config = proto.Field(proto.MESSAGE, number=13, message="TestConfig",) - test_case_conversation_turns = proto.RepeatedField( proto.MESSAGE, number=5, message="ConversationTurn", ) - - creation_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - + creation_time = proto.Field( + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, + ) last_test_result = proto.Field(proto.MESSAGE, number=12, message="TestCaseResult",) @@ -152,22 +144,17 @@ class TestCaseResult(proto.Message): The time that the test was run. """ - name = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) conversation_turns = proto.RepeatedField( proto.MESSAGE, number=3, message="ConversationTurn", ) - test_result = proto.Field(proto.ENUM, number=4, enum="TestResult",) - - test_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + test_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) class TestConfig(proto.Message): r"""Represents configurations for a test case. - Attributes: tracking_parameters (Sequence[str]): Session parameters to be compared when @@ -178,9 +165,8 @@ class TestConfig(proto.Message): ``projects//locations//agents//flows/``. """ - tracking_parameters = proto.RepeatedField(proto.STRING, number=1) - - flow = proto.Field(proto.STRING, number=2) + tracking_parameters = proto.RepeatedField(proto.STRING, number=1,) + flow = proto.Field(proto.STRING, number=2,) class ConversationTurn(proto.Message): @@ -196,7 +182,6 @@ class ConversationTurn(proto.Message): class UserInput(proto.Message): r"""The input from the human user. - Attributes: input (google.cloud.dialogflowcx_v3beta1.types.QueryInput): Supports [text @@ -217,16 +202,13 @@ class UserInput(proto.Message): """ input = proto.Field(proto.MESSAGE, number=5, message=session.QueryInput,) - injected_parameters = proto.Field( - proto.MESSAGE, number=2, message=struct.Struct, + proto.MESSAGE, number=2, message=struct_pb2.Struct, ) - - is_webhook_enabled = proto.Field(proto.BOOL, number=3) + is_webhook_enabled = proto.Field(proto.BOOL, number=3,) class VirtualAgentOutput(proto.Message): r"""The output from the virtual agent. - Attributes: session_parameters (google.protobuf.struct_pb2.Struct): The session parameters available to the bot @@ -258,29 +240,24 @@ class VirtualAgentOutput(proto.Message): """ session_parameters = proto.Field( - proto.MESSAGE, number=4, message=struct.Struct, + proto.MESSAGE, number=4, message=struct_pb2.Struct, ) - differences = proto.RepeatedField( proto.MESSAGE, number=5, message="TestRunDifference", ) - - diagnostic_info = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - + diagnostic_info = proto.Field( + proto.MESSAGE, number=6, message=struct_pb2.Struct, + ) triggered_intent = proto.Field( proto.MESSAGE, number=7, message=gcdc_intent.Intent, ) - current_page = proto.Field(proto.MESSAGE, number=8, message=gcdc_page.Page,) - text_responses = proto.RepeatedField( proto.MESSAGE, number=9, message=response_message.ResponseMessage.Text, ) - - status = proto.Field(proto.MESSAGE, number=10, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=10, message=status_pb2.Status,) user_input = proto.Field(proto.MESSAGE, number=1, message=UserInput,) - virtual_agent_output = proto.Field( proto.MESSAGE, number=2, message=VirtualAgentOutput, ) @@ -307,8 +284,7 @@ class DiffType(proto.Enum): UTTERANCE = 4 type_ = proto.Field(proto.ENUM, number=1, enum=DiffType,) - - description = proto.Field(proto.STRING, number=2) + description = proto.Field(proto.STRING, number=2,) class TransitionCoverage(proto.Message): @@ -327,7 +303,6 @@ class TransitionCoverage(proto.Message): class TransitionNode(proto.Message): r"""The source or target of a transition. - Attributes: page (google.cloud.dialogflowcx_v3beta1.types.Page): Indicates a transition to a @@ -342,14 +317,12 @@ class TransitionNode(proto.Message): page = proto.Field( proto.MESSAGE, number=1, oneof="kind", message=gcdc_page.Page, ) - flow = proto.Field( proto.MESSAGE, number=2, oneof="kind", message=gcdc_flow.Flow, ) class Transition(proto.Message): r"""A transition in a page. - Attributes: source (google.cloud.dialogflowcx_v3beta1.types.TransitionCoverage.TransitionNode): The start node of a transition. @@ -370,26 +343,20 @@ class Transition(proto.Message): source = proto.Field( proto.MESSAGE, number=1, message="TransitionCoverage.TransitionNode", ) - - index = proto.Field(proto.INT32, number=4) - + index = proto.Field(proto.INT32, number=4,) target = proto.Field( proto.MESSAGE, number=2, message="TransitionCoverage.TransitionNode", ) - - covered = proto.Field(proto.BOOL, number=3) - + covered = proto.Field(proto.BOOL, number=3,) transition_route = proto.Field( proto.MESSAGE, number=5, oneof="detail", message=gcdc_page.TransitionRoute, ) - event_handler = proto.Field( proto.MESSAGE, number=6, oneof="detail", message=gcdc_page.EventHandler, ) transitions = proto.RepeatedField(proto.MESSAGE, number=1, message=Transition,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class TransitionRouteGroupCoverage(proto.Message): @@ -408,7 +375,6 @@ class TransitionRouteGroupCoverage(proto.Message): class Coverage(proto.Message): r"""Coverage result message for one transition route group. - Attributes: route_group (google.cloud.dialogflowcx_v3beta1.types.TransitionRouteGroup): Transition route group metadata. Only name @@ -423,7 +389,6 @@ class Coverage(proto.Message): class Transition(proto.Message): r"""A transition coverage in a transition route group. - Attributes: transition_route (google.cloud.dialogflowcx_v3beta1.types.TransitionRoute): Intent route or condition route. @@ -436,26 +401,22 @@ class Transition(proto.Message): transition_route = proto.Field( proto.MESSAGE, number=1, message=gcdc_page.TransitionRoute, ) - - covered = proto.Field(proto.BOOL, number=2) + covered = proto.Field(proto.BOOL, number=2,) route_group = proto.Field( proto.MESSAGE, number=1, message=transition_route_group.TransitionRouteGroup, ) - transitions = proto.RepeatedField( proto.MESSAGE, number=2, message="TransitionRouteGroupCoverage.Coverage.Transition", ) - - coverage_score = proto.Field(proto.FLOAT, number=3) + coverage_score = proto.Field(proto.FLOAT, number=3,) coverages = proto.RepeatedField(proto.MESSAGE, number=1, message=Coverage,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class IntentCoverage(proto.Message): @@ -473,7 +434,6 @@ class IntentCoverage(proto.Message): class Intent(proto.Message): r"""The agent's intent. - Attributes: intent (str): The intent full resource name @@ -482,13 +442,11 @@ class Intent(proto.Message): least one of the agent's test cases. """ - intent = proto.Field(proto.STRING, number=1) - - covered = proto.Field(proto.BOOL, number=2) + intent = proto.Field(proto.STRING, number=1,) + covered = proto.Field(proto.BOOL, number=2,) intents = proto.RepeatedField(proto.MESSAGE, number=1, message=Intent,) - - coverage_score = proto.Field(proto.FLOAT, number=2) + coverage_score = proto.Field(proto.FLOAT, number=2,) class CalculateCoverageRequest(proto.Message): @@ -510,8 +468,7 @@ class CoverageType(proto.Enum): PAGE_TRANSITION = 2 TRANSITION_ROUTE_GROUP = 3 - agent = proto.Field(proto.STRING, number=3) - + agent = proto.Field(proto.STRING, number=3,) type_ = proto.Field(proto.ENUM, number=2, enum=CoverageType,) @@ -532,16 +489,13 @@ class CalculateCoverageResponse(proto.Message): Transition route group coverage. """ - agent = proto.Field(proto.STRING, number=5) - + agent = proto.Field(proto.STRING, number=5,) intent_coverage = proto.Field( proto.MESSAGE, number=2, oneof="coverage_type", message="IntentCoverage", ) - transition_coverage = proto.Field( proto.MESSAGE, number=4, oneof="coverage_type", message="TransitionCoverage", ) - route_group_coverage = proto.Field( proto.MESSAGE, number=6, @@ -580,12 +534,9 @@ class TestCaseView(proto.Enum): BASIC = 1 FULL = 2 - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) view = proto.Field(proto.ENUM, number=4, enum=TestCaseView,) @@ -608,8 +559,7 @@ def raw_page(self): return self test_cases = proto.RepeatedField(proto.MESSAGE, number=1, message="TestCase",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class BatchDeleteTestCasesRequest(proto.Message): @@ -625,9 +575,8 @@ class BatchDeleteTestCasesRequest(proto.Message): ``projects//locations/ /agents//testCases/``. """ - parent = proto.Field(proto.STRING, number=1) - - names = proto.RepeatedField(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + names = proto.RepeatedField(proto.STRING, number=3,) class CreateTestCaseRequest(proto.Message): @@ -642,8 +591,7 @@ class CreateTestCaseRequest(proto.Message): Required. The test case to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) test_case = proto.Field(proto.MESSAGE, number=2, message="TestCase",) @@ -664,8 +612,9 @@ class UpdateTestCaseRequest(proto.Message): """ test_case = proto.Field(proto.MESSAGE, number=1, message="TestCase",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class GetTestCaseRequest(proto.Message): @@ -678,7 +627,7 @@ class GetTestCaseRequest(proto.Message): ``projects//locations//agents//testCases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class RunTestCaseRequest(proto.Message): @@ -695,9 +644,8 @@ class RunTestCaseRequest(proto.Message): ``projects//locations//agents//environments/``. """ - name = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) class RunTestCaseResponse(proto.Message): @@ -716,7 +664,7 @@ class RunTestCaseMetadata(proto.Message): r"""Metadata returned for the [TestCases.RunTestCase][google.cloud.dialogflow.cx.v3beta1.TestCases.RunTestCase] long running operation. - """ + """ class BatchRunTestCasesRequest(proto.Message): @@ -735,11 +683,9 @@ class BatchRunTestCasesRequest(proto.Message): ``projects//locations//agents//testCases/``. """ - parent = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) - - test_cases = proto.RepeatedField(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) + test_cases = proto.RepeatedField(proto.STRING, number=3,) class BatchRunTestCasesResponse(proto.Message): @@ -771,7 +717,6 @@ class BatchRunTestCasesMetadata(proto.Message): class TestError(proto.Message): r"""Error info for running a test. - Attributes: test_case (str): The test case resource name. @@ -781,11 +726,9 @@ class TestError(proto.Message): The timestamp when the test was completed. """ - test_case = proto.Field(proto.STRING, number=1) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - - test_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + test_case = proto.Field(proto.STRING, number=1,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) + test_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class ImportTestCasesRequest(proto.Message): @@ -805,11 +748,9 @@ class ImportTestCasesRequest(proto.Message): Uncompressed raw byte content for test cases. """ - parent = proto.Field(proto.STRING, number=1) - - gcs_uri = proto.Field(proto.STRING, number=2, oneof="source") - - content = proto.Field(proto.BYTES, number=3, oneof="source") + parent = proto.Field(proto.STRING, number=1,) + gcs_uri = proto.Field(proto.STRING, number=2, oneof="source",) + content = proto.Field(proto.BYTES, number=3, oneof="source",) class ImportTestCasesResponse(proto.Message): @@ -822,7 +763,7 @@ class ImportTestCasesResponse(proto.Message): ``projects//locations//agents//testCases/``. """ - names = proto.RepeatedField(proto.STRING, number=1) + names = proto.RepeatedField(proto.STRING, number=1,) class ImportTestCasesMetadata(proto.Message): @@ -840,7 +781,6 @@ class ImportTestCasesMetadata(proto.Message): class TestCaseError(proto.Message): r"""Error info for importing a test. - Attributes: test_case (google.cloud.dialogflowcx_v3beta1.types.TestCase): The test case. @@ -849,8 +789,7 @@ class TestCaseError(proto.Message): """ test_case = proto.Field(proto.MESSAGE, number=1, message="TestCase",) - - status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) + status = proto.Field(proto.MESSAGE, number=2, message=status_pb2.Status,) class ExportTestCasesRequest(proto.Message): @@ -889,13 +828,10 @@ class DataFormat(proto.Enum): BLOB = 1 JSON = 2 - parent = proto.Field(proto.STRING, number=1) - - gcs_uri = proto.Field(proto.STRING, number=2, oneof="destination") - + parent = proto.Field(proto.STRING, number=1,) + gcs_uri = proto.Field(proto.STRING, number=2, oneof="destination",) data_format = proto.Field(proto.ENUM, number=3, enum=DataFormat,) - - filter = proto.Field(proto.STRING, number=4) + filter = proto.Field(proto.STRING, number=4,) class ExportTestCasesResponse(proto.Message): @@ -911,16 +847,15 @@ class ExportTestCasesResponse(proto.Message): Uncompressed raw byte content for test cases. """ - gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination") - - content = proto.Field(proto.BYTES, number=2, oneof="destination") + gcs_uri = proto.Field(proto.STRING, number=1, oneof="destination",) + content = proto.Field(proto.BYTES, number=2, oneof="destination",) class ExportTestCasesMetadata(proto.Message): r"""Metadata returned for the [TestCases.ExportTestCases][google.cloud.dialogflow.cx.v3beta1.TestCases.ExportTestCases] long running operation. - """ + """ class ListTestCaseResultsRequest(proto.Message): @@ -967,13 +902,10 @@ class ListTestCaseResultsRequest(proto.Message): 1602540713. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - filter = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + filter = proto.Field(proto.STRING, number=4,) class ListTestCaseResultsResponse(proto.Message): @@ -996,8 +928,20 @@ def raw_page(self): test_case_results = proto.RepeatedField( proto.MESSAGE, number=1, message="TestCaseResult", ) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetTestCaseResultRequest(proto.Message): + r"""The request message for + [TestCases.GetTestCaseResult][google.cloud.dialogflow.cx.v3beta1.TestCases.GetTestCaseResult]. + + Attributes: + name (str): + Required. The name of the testcase. Format: + ``projects//locations//agents//testCases//results/``. + """ - next_page_token = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py b/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py index 550bdd44..456e4bc3 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py +++ b/google/cloud/dialogflowcx_v3beta1/types/transition_route_group.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import page -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -57,10 +54,8 @@ class TransitionRouteGroup(proto.Message): [TransitionRouteGroup][google.cloud.dialogflow.cx.v3beta1.TransitionRouteGroup]. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) transition_routes = proto.RepeatedField( proto.MESSAGE, number=5, message=page.TransitionRoute, ) @@ -82,11 +77,13 @@ class ListTransitionRouteGroupsRequest(proto.Message): The next_page_token value returned from a previous list request. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - is language dependent. + The language to list transition route groups for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -95,13 +92,10 @@ class ListTransitionRouteGroupsRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) - - language_code = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + language_code = proto.Field(proto.STRING, number=4,) class ListTransitionRouteGroupsResponse(proto.Message): @@ -128,8 +122,7 @@ def raw_page(self): transition_route_groups = proto.RepeatedField( proto.MESSAGE, number=1, message="TransitionRouteGroup", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetTransitionRouteGroupRequest(proto.Message): @@ -143,11 +136,13 @@ class GetTransitionRouteGroupRequest(proto.Message): Format: ``projects//locations//agents//flows//transitionRouteGroups/``. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - is language dependent. + The language to retrieve the transition route group for. The + following fields are language dependent: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -156,9 +151,8 @@ class GetTransitionRouteGroupRequest(proto.Message): before they can be used. """ - name = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class CreateTransitionRouteGroupRequest(proto.Message): @@ -175,11 +169,13 @@ class CreateTransitionRouteGroupRequest(proto.Message): Required. The transition route group to create. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - is language dependent. + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -188,13 +184,11 @@ class CreateTransitionRouteGroupRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) transition_route_group = proto.Field( proto.MESSAGE, number=2, message="TransitionRouteGroup", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class UpdateTransitionRouteGroupRequest(proto.Message): @@ -208,11 +202,13 @@ class UpdateTransitionRouteGroupRequest(proto.Message): update_mask (google.protobuf.field_mask_pb2.FieldMask): The mask to control which fields get updated. language_code (str): - The language to list transition route groups for. The field - [``messages``][TransitionRoute.trigger_fulfillment.messages] - in - [TransitionRoute][google.cloud.dialogflow.cx.v3beta1.TransitionRoute] - is language dependent. + The language of the following fields in + ``TransitionRouteGroup``: + + - ``TransitionRouteGroup.transition_routes.trigger_fulfillment.messages`` + - + + ``TransitionRouteGroup.transition_routes.trigger_fulfillment.conditional_cases`` If not specified, the agent's default language is used. `Many @@ -224,10 +220,10 @@ class UpdateTransitionRouteGroupRequest(proto.Message): transition_route_group = proto.Field( proto.MESSAGE, number=1, message="TransitionRouteGroup", ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) - - language_code = proto.Field(proto.STRING, number=3) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + language_code = proto.Field(proto.STRING, number=3,) class DeleteTransitionRouteGroupRequest(proto.Message): @@ -252,9 +248,8 @@ class DeleteTransitionRouteGroupRequest(proto.Message): transition route group, as well as any reference to it. """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/validation_message.py b/google/cloud/dialogflowcx_v3beta1/types/validation_message.py index b49e957a..f38e2190 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/validation_message.py +++ b/google/cloud/dialogflowcx_v3beta1/types/validation_message.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class ValidationMessage(proto.Message): r"""Agent/flow validation message. - Attributes: resource_type (google.cloud.dialogflowcx_v3beta1.types.ValidationMessage.ResourceType): The type of the resources where the message @@ -68,21 +65,16 @@ class Severity(proto.Enum): ERROR = 3 resource_type = proto.Field(proto.ENUM, number=1, enum=ResourceType,) - - resources = proto.RepeatedField(proto.STRING, number=2) - + resources = proto.RepeatedField(proto.STRING, number=2,) resource_names = proto.RepeatedField( proto.MESSAGE, number=6, message="ResourceName", ) - severity = proto.Field(proto.ENUM, number=3, enum=Severity,) - - detail = proto.Field(proto.STRING, number=4) + detail = proto.Field(proto.STRING, number=4,) class ResourceName(proto.Message): r"""Resource name and display name. - Attributes: name (str): Name. @@ -90,9 +82,8 @@ class ResourceName(proto.Message): Display name. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/version.py b/google/cloud/dialogflowcx_v3beta1/types/version.py index 438ab88f..d18a7247 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/version.py +++ b/google/cloud/dialogflowcx_v3beta1/types/version.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import flow -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -49,12 +46,11 @@ class CreateVersionOperationMetadata(proto.Message): ``projects//locations//agents//flows//versions/``. """ - version = proto.Field(proto.STRING, number=1) + version = proto.Field(proto.STRING, number=1,) class Version(proto.Message): r"""Represents a version of a flow. - Attributes: name (str): Format: projects//locations//agents//flows//versions/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateVersionRequest(proto.Message): @@ -180,8 +168,7 @@ class CreateVersionRequest(proto.Message): Required. The version to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) version = proto.Field(proto.MESSAGE, number=2, message="Version",) @@ -199,8 +186,9 @@ class UpdateVersionRequest(proto.Message): """ version = proto.Field(proto.MESSAGE, number=1, message="Version",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteVersionRequest(proto.Message): @@ -215,7 +203,7 @@ class DeleteVersionRequest(proto.Message): ``projects//locations//agents//flows//versions/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class LoadVersionRequest(proto.Message): @@ -226,20 +214,18 @@ class LoadVersionRequest(proto.Message): name (str): Required. The [Version][google.cloud.dialogflow.cx.v3beta1.Version] to be - loaded to draft version. Format: + loaded to draft flow. Format: ``projects//locations//agents//flows//versions/``. allow_override_agent_resources (bool): This field is used to prevent accidental overwrite of other - agent resources in the draft version, which can potentially - impact other flow's behavior. If - ``allow_override_agent_resources`` is false, conflicted - agent-level resources will not be overridden (i.e. intents, - entities, webhooks). + agent resources, which can potentially impact other flow's + behavior. If ``allow_override_agent_resources`` is false, + conflicted agent-level resources will not be overridden + (i.e. intents, entities, webhooks). """ - name = proto.Field(proto.STRING, number=1) - - allow_override_agent_resources = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + allow_override_agent_resources = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflowcx_v3beta1/types/webhook.py b/google/cloud/dialogflowcx_v3beta1/types/webhook.py index dfbdd085..2fc49e77 100644 --- a/google/cloud/dialogflowcx_v3beta1/types/webhook.py +++ b/google/cloud/dialogflowcx_v3beta1/types/webhook.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflowcx_v3beta1.types import response_message -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -62,6 +59,10 @@ 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. + service_directory (google.cloud.dialogflowcx_v3beta1.types.Webhook.ServiceDirectoryConfig): + Configuration for a `Service + Directory `__ + service. timeout (google.protobuf.duration_pb2.Duration): Webhook execution timeout. Execution is considered failed if Dialogflow doesn't receive @@ -74,7 +75,6 @@ class Webhook(proto.Message): class GenericWebService(proto.Message): r"""Represents configuration for a generic web service. - Attributes: uri (str): Required. The webhook URI for receiving POST @@ -88,25 +88,43 @@ class GenericWebService(proto.Message): with webhook requests. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + username = proto.Field(proto.STRING, number=2,) + password = proto.Field(proto.STRING, number=3,) + request_headers = proto.MapField(proto.STRING, proto.STRING, number=4,) - username = proto.Field(proto.STRING, number=2) + class ServiceDirectoryConfig(proto.Message): + r"""Represents configuration for a `Service + Directory `__ service. - password = proto.Field(proto.STRING, number=3) - - request_headers = proto.MapField(proto.STRING, proto.STRING, number=4) - - name = proto.Field(proto.STRING, number=1) + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``Location ID`` of the service directory must be the same as + the location of the agent. + generic_web_service (google.cloud.dialogflowcx_v3beta1.types.Webhook.GenericWebService): + Generic Service configuration of this + webhook. + """ - display_name = proto.Field(proto.STRING, number=2) + service = proto.Field(proto.STRING, number=1,) + generic_web_service = proto.Field( + proto.MESSAGE, number=2, message="Webhook.GenericWebService", + ) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) generic_web_service = proto.Field( proto.MESSAGE, number=4, oneof="webhook", message=GenericWebService, ) - - timeout = proto.Field(proto.MESSAGE, number=6, message=duration.Duration,) - - disabled = proto.Field(proto.BOOL, number=5) + service_directory = proto.Field( + proto.MESSAGE, number=7, oneof="webhook", message=ServiceDirectoryConfig, + ) + timeout = proto.Field(proto.MESSAGE, number=6, message=duration_pb2.Duration,) + disabled = proto.Field(proto.BOOL, number=5,) class ListWebhooksRequest(proto.Message): @@ -125,11 +143,9 @@ class ListWebhooksRequest(proto.Message): request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListWebhooksResponse(proto.Message): @@ -151,8 +167,7 @@ def raw_page(self): return self webhooks = proto.RepeatedField(proto.MESSAGE, number=1, message="Webhook",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetWebhookRequest(proto.Message): @@ -165,7 +180,7 @@ class GetWebhookRequest(proto.Message): ``projects//locations//agents//webhooks/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateWebhookRequest(proto.Message): @@ -180,8 +195,7 @@ class CreateWebhookRequest(proto.Message): Required. The webhook to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) webhook = proto.Field(proto.MESSAGE, number=2, message="Webhook",) @@ -199,8 +213,9 @@ class UpdateWebhookRequest(proto.Message): """ webhook = proto.Field(proto.MESSAGE, number=1, message="Webhook",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteWebhookRequest(proto.Message): @@ -226,19 +241,43 @@ class DeleteWebhookRequest(proto.Message): fulfillments that point to this webhook will be removed). """ - name = proto.Field(proto.STRING, number=1) - - force = proto.Field(proto.BOOL, number=2) + name = proto.Field(proto.STRING, number=1,) + force = proto.Field(proto.BOOL, number=2,) class WebhookRequest(proto.Message): - r"""The request message for a webhook call. + r"""The request message for a webhook call. The request is sent + as a JSON object and the field names will be presented in camel + cases. Attributes: detect_intent_response_id (str): Always present. The unique identifier of the [DetectIntentResponse][google.cloud.dialogflow.cx.v3beta1.DetectIntentResponse] that will be returned to the API caller. + 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. + 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/``. + 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. + 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. + language_code (str): + The language code specified in the [original + request][QueryInput.language_code]. fulfillment_info (google.cloud.dialogflowcx_v3beta1.types.WebhookRequest.FulfillmentInfo): Always present. Information about the fulfillment that triggered this webhook call. @@ -272,11 +311,10 @@ class FulfillmentInfo(proto.Message): which fulfillment is being called. """ - tag = proto.Field(proto.STRING, number=1) + tag = proto.Field(proto.STRING, number=1,) class IntentInfo(proto.Message): r"""Represents intent information communicated to the webhook. - Attributes: last_matched_intent (str): Always present. The unique identifier of the last matched @@ -300,7 +338,6 @@ class IntentInfo(proto.Message): class IntentParameterValue(proto.Message): r"""Represents a value for an intent parameter. - Attributes: original_value (str): Always present. Original text value extracted @@ -310,26 +347,23 @@ class IntentParameterValue(proto.Message): parameter extracted from user utterance. """ - original_value = proto.Field(proto.STRING, number=1) - - resolved_value = proto.Field(proto.MESSAGE, number=2, message=struct.Value,) - - last_matched_intent = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=3) + original_value = proto.Field(proto.STRING, number=1,) + resolved_value = proto.Field( + proto.MESSAGE, number=2, message=struct_pb2.Value, + ) + last_matched_intent = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=3,) parameters = proto.MapField( proto.STRING, proto.MESSAGE, number=2, message="WebhookRequest.IntentInfo.IntentParameterValue", ) - - confidence = proto.Field(proto.FLOAT, number=4) + confidence = proto.Field(proto.FLOAT, number=4,) class SentimentAnalysisResult(proto.Message): r"""Represents the result of sentiment analysis. - Attributes: score (float): Sentiment score between -1.0 (negative @@ -340,26 +374,23 @@ class SentimentAnalysisResult(proto.Message): of score (positive or negative). """ - score = proto.Field(proto.FLOAT, number=1) - - magnitude = proto.Field(proto.FLOAT, number=2) - - detect_intent_response_id = proto.Field(proto.STRING, number=1) + score = proto.Field(proto.FLOAT, number=1,) + magnitude = proto.Field(proto.FLOAT, number=2,) + detect_intent_response_id = proto.Field(proto.STRING, number=1,) + text = proto.Field(proto.STRING, number=10, oneof="query",) + trigger_intent = proto.Field(proto.STRING, number=11, oneof="query",) + transcript = proto.Field(proto.STRING, number=12, oneof="query",) + trigger_event = proto.Field(proto.STRING, number=14, oneof="query",) + language_code = proto.Field(proto.STRING, number=15,) fulfillment_info = proto.Field(proto.MESSAGE, number=6, message=FulfillmentInfo,) - intent_info = proto.Field(proto.MESSAGE, number=3, message=IntentInfo,) - page_info = proto.Field(proto.MESSAGE, number=4, message="PageInfo",) - session_info = proto.Field(proto.MESSAGE, number=5, message="SessionInfo",) - messages = proto.RepeatedField( proto.MESSAGE, number=7, message=response_message.ResponseMessage, ) - - payload = proto.Field(proto.MESSAGE, number=8, message=struct.Struct,) - + payload = proto.Field(proto.MESSAGE, number=8, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=9, message=SentimentAnalysisResult, ) @@ -367,7 +398,6 @@ class SentimentAnalysisResult(proto.Message): class WebhookResponse(proto.Message): r"""The response message for a webhook call. - Attributes: fulfillment_response (google.cloud.dialogflowcx_v3beta1.types.WebhookResponse.FulfillmentResponse): The fulfillment response to send to the user. @@ -395,7 +425,6 @@ class WebhookResponse(proto.Message): class FulfillmentResponse(proto.Message): r"""Represents a fulfillment response to the user. - Attributes: messages (Sequence[google.cloud.dialogflowcx_v3beta1.types.ResponseMessage]): The list of rich message responses to present @@ -413,7 +442,6 @@ class MergeBehavior(proto.Enum): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=response_message.ResponseMessage, ) - merge_behavior = proto.Field( proto.ENUM, number=2, @@ -423,16 +451,11 @@ class MergeBehavior(proto.Enum): fulfillment_response = proto.Field( proto.MESSAGE, number=1, message=FulfillmentResponse, ) - page_info = proto.Field(proto.MESSAGE, number=2, message="PageInfo",) - session_info = proto.Field(proto.MESSAGE, number=3, message="SessionInfo",) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - target_page = proto.Field(proto.STRING, number=5, oneof="transition") - - target_flow = proto.Field(proto.STRING, number=6, oneof="transition") + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + target_page = proto.Field(proto.STRING, number=5, oneof="transition",) + target_flow = proto.Field(proto.STRING, number=6, oneof="transition",) class PageInfo(proto.Message): @@ -457,7 +480,6 @@ class PageInfo(proto.Message): class FormInfo(proto.Message): r"""Represents form information. - Attributes: parameter_info (Sequence[google.cloud.dialogflowcx_v3beta1.types.PageInfo.FormInfo.ParameterInfo]): Optional for both @@ -470,7 +492,6 @@ class FormInfo(proto.Message): class ParameterInfo(proto.Message): r"""Represents parameter information. - Attributes: display_name (str): Always present for @@ -520,26 +541,21 @@ class ParameterState(proto.Enum): INVALID = 2 FILLED = 3 - display_name = proto.Field(proto.STRING, number=1) - - required = proto.Field(proto.BOOL, number=2) - + display_name = proto.Field(proto.STRING, number=1,) + required = proto.Field(proto.BOOL, number=2,) state = proto.Field( proto.ENUM, number=3, enum="PageInfo.FormInfo.ParameterInfo.ParameterState", ) - - value = proto.Field(proto.MESSAGE, number=4, message=struct.Value,) - - just_collected = proto.Field(proto.BOOL, number=5) + value = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Value,) + just_collected = proto.Field(proto.BOOL, number=5,) parameter_info = proto.RepeatedField( proto.MESSAGE, number=2, message="PageInfo.FormInfo.ParameterInfo", ) - current_page = proto.Field(proto.STRING, number=1) - + current_page = proto.Field(proto.STRING, number=1,) form_info = proto.Field(proto.MESSAGE, number=3, message=FormInfo,) @@ -574,10 +590,9 @@ class SessionInfo(proto.Message): The map is keyed by parameters' display names. """ - session = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=1,) parameters = proto.MapField( - proto.STRING, proto.MESSAGE, number=2, message=struct.Value, + proto.STRING, proto.MESSAGE, number=2, message=struct_pb2.Value, ) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/tests/unit/gapic/dialogflowcx_v3/__init__.py b/tests/unit/gapic/dialogflowcx_v3/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/dialogflowcx_v3/__init__.py +++ b/tests/unit/gapic/dialogflowcx_v3/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/dialogflowcx_v3/test_agents.py b/tests/unit/gapic/dialogflowcx_v3/test_agents.py index 64e50b3e..83921c26 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_agents.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_agents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.agents import AgentsAsyncClient 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 ( + _API_CORE_VERSION, +) +from google.cloud.dialogflowcx_v3.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflowcx_v3.types import agent from google.cloud.dialogflowcx_v3.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3.types import flow from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_agents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_agents_client_get_transport_class(): def test_agents_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(AgentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_agents_client_client_options_from_dict(): def test_list_agents(transport: str = "grpc", request_type=agent.ListAgentsRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -431,19 +460,15 @@ def test_list_agents(transport: str = "grpc", request_type=agent.ListAgentsReque call.return_value = agent.ListAgentsResponse( next_page_token="next_page_token_value", ) - response = client.list_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -455,7 +480,7 @@ def test_list_agents_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -463,7 +488,6 @@ def test_list_agents_empty_call(): client.list_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() @@ -472,7 +496,7 @@ async def test_list_agents_async( transport: str = "grpc_asyncio", request_type=agent.ListAgentsRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,18 +509,15 @@ async def test_list_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.ListAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -506,17 +527,17 @@ async def test_list_agents_async_from_dict(): def test_list_agents_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ListAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: call.return_value = agent.ListAgentsResponse() - client.list_agents(request) # Establish that the underlying gRPC stub method was called. @@ -531,11 +552,12 @@ def test_list_agents_field_headers(): @pytest.mark.asyncio async def test_list_agents_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ListAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ async def test_list_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.ListAgentsResponse() ) - await client.list_agents(request) # Establish that the underlying gRPC stub method was called. @@ -557,13 +578,12 @@ async def test_list_agents_field_headers_async(): def test_list_agents_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.ListAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_agents(parent="parent_value",) @@ -572,12 +592,11 @@ def test_list_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_agents_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -589,7 +608,7 @@ def test_list_agents_flattened_error(): @pytest.mark.asyncio async def test_list_agents_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -607,13 +626,12 @@ async def test_list_agents_flattened_async(): # 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_agents_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -624,7 +642,7 @@ async def test_list_agents_flattened_error_async(): def test_list_agents_pager(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -654,7 +672,7 @@ def test_list_agents_pager(): def test_list_agents_pages(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -676,7 +694,7 @@ def test_list_agents_pages(): @pytest.mark.asyncio async def test_list_agents_async_pager(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,7 +723,7 @@ async def test_list_agents_async_pager(): @pytest.mark.asyncio async def test_list_agents_async_pages(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -731,7 +749,7 @@ async def test_list_agents_async_pages(): def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -745,6 +763,7 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -753,37 +772,25 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -795,7 +802,7 @@ def test_get_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -803,7 +810,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -812,7 +818,7 @@ async def test_get_agent_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -827,6 +833,7 @@ async def test_get_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -836,36 +843,25 @@ async def test_get_agent_async( enable_spell_correction=True, ) ) - response = await client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -875,17 +871,17 @@ async def test_get_agent_async_from_dict(): def test_get_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.GetAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = agent.Agent() - client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -900,17 +896,17 @@ def test_get_agent_field_headers(): @pytest.mark.asyncio async def test_get_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.GetAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -924,13 +920,12 @@ async def test_get_agent_field_headers_async(): def test_get_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent(name="name_value",) @@ -939,12 +934,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +950,7 @@ def test_get_agent_flattened_error(): @pytest.mark.asyncio async def test_get_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: @@ -972,13 +966,12 @@ async def test_get_agent_flattened_async(): # 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_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -992,7 +985,7 @@ def test_create_agent( transport: str = "grpc", request_type=gcdc_agent.CreateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1006,6 +999,7 @@ def test_create_agent( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1014,37 +1008,25 @@ def test_create_agent( enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.create_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1056,7 +1038,7 @@ def test_create_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1046,6 @@ def test_create_agent_empty_call(): client.create_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() @@ -1073,7 +1054,7 @@ async def test_create_agent_async( transport: str = "grpc_asyncio", request_type=gcdc_agent.CreateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1088,6 +1069,7 @@ async def test_create_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1097,36 +1079,25 @@ async def test_create_agent_async( enable_spell_correction=True, ) ) - response = await client.create_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1136,17 +1107,17 @@ async def test_create_agent_async_from_dict(): def test_create_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = gcdc_agent.CreateAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: call.return_value = gcdc_agent.Agent() - client.create_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1161,17 +1132,17 @@ def test_create_agent_field_headers(): @pytest.mark.asyncio async def test_create_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = gcdc_agent.CreateAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.create_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1185,13 +1156,12 @@ async def test_create_agent_field_headers_async(): def test_create_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_agent( @@ -1202,14 +1172,12 @@ def test_create_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].agent == gcdc_agent.Agent(name="name_value") def test_create_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1223,7 +1191,7 @@ def test_create_agent_flattened_error(): @pytest.mark.asyncio async def test_create_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: @@ -1241,15 +1209,13 @@ async def test_create_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].agent == gcdc_agent.Agent(name="name_value") @pytest.mark.asyncio async def test_create_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1265,7 +1231,7 @@ def test_update_agent( transport: str = "grpc", request_type=gcdc_agent.UpdateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1279,6 +1245,7 @@ def test_update_agent( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1287,37 +1254,25 @@ def test_update_agent( enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.update_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1329,7 +1284,7 @@ def test_update_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1337,7 +1292,6 @@ def test_update_agent_empty_call(): client.update_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() @@ -1346,7 +1300,7 @@ async def test_update_agent_async( transport: str = "grpc_asyncio", request_type=gcdc_agent.UpdateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1361,6 +1315,7 @@ async def test_update_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1370,36 +1325,25 @@ async def test_update_agent_async( enable_spell_correction=True, ) ) - response = await client.update_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1409,17 +1353,17 @@ async def test_update_agent_async_from_dict(): def test_update_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = gcdc_agent.UpdateAgentRequest() + request.agent.name = "agent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: call.return_value = gcdc_agent.Agent() - client.update_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1434,17 +1378,17 @@ def test_update_agent_field_headers(): @pytest.mark.asyncio async def test_update_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = gcdc_agent.UpdateAgentRequest() + request.agent.name = "agent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.update_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1458,32 +1402,29 @@ async def test_update_agent_field_headers_async(): def test_update_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_agent( agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1491,13 +1432,13 @@ def test_update_agent_flattened_error(): client.update_agent( gcdc_agent.UpdateAgentRequest(), agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: @@ -1509,22 +1450,20 @@ async def test_update_agent_flattened_async(): # using the keyword arguments to the method. response = await client.update_agent( agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1532,13 +1471,13 @@ async def test_update_agent_flattened_error_async(): await client.update_agent( gcdc_agent.UpdateAgentRequest(), agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1549,13 +1488,11 @@ def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentReq with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1570,7 +1507,7 @@ def test_delete_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1578,7 +1515,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1587,7 +1523,7 @@ async def test_delete_agent_async( transport: str = "grpc_asyncio", request_type=agent.DeleteAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1598,13 +1534,11 @@ async def test_delete_agent_async( with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1617,17 +1551,17 @@ async def test_delete_agent_async_from_dict(): def test_delete_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.DeleteAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = None - client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1642,17 +1576,17 @@ def test_delete_agent_field_headers(): @pytest.mark.asyncio async def test_delete_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.DeleteAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1666,13 +1600,12 @@ async def test_delete_agent_field_headers_async(): def test_delete_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_agent(name="name_value",) @@ -1681,12 +1614,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1698,7 +1630,7 @@ def test_delete_agent_flattened_error(): @pytest.mark.asyncio async def test_delete_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: @@ -1714,13 +1646,12 @@ async def test_delete_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1732,7 +1663,7 @@ async def test_delete_agent_flattened_error_async(): def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1743,13 +1674,11 @@ def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentReq with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1764,7 +1693,7 @@ def test_export_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1772,7 +1701,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1781,7 +1709,7 @@ async def test_export_agent_async( transport: str = "grpc_asyncio", request_type=agent.ExportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1794,13 +1722,11 @@ async def test_export_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1813,17 +1739,17 @@ async def test_export_agent_async_from_dict(): def test_export_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ExportAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1838,11 +1764,12 @@ def test_export_agent_field_headers(): @pytest.mark.asyncio async def test_export_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ExportAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1850,7 +1777,6 @@ async def test_export_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1865,7 +1791,7 @@ async def test_export_agent_field_headers_async(): def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1876,13 +1802,11 @@ def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentR with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -1897,7 +1821,7 @@ def test_restore_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1905,7 +1829,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -1914,7 +1837,7 @@ async def test_restore_agent_async( transport: str = "grpc_asyncio", request_type=agent.RestoreAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1927,13 +1850,11 @@ async def test_restore_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -1946,17 +1867,17 @@ async def test_restore_agent_async_from_dict(): def test_restore_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.RestoreAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1971,11 +1892,12 @@ def test_restore_agent_field_headers(): @pytest.mark.asyncio async def test_restore_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.RestoreAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1983,7 +1905,6 @@ async def test_restore_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2000,7 +1921,7 @@ def test_validate_agent( transport: str = "grpc", request_type=agent.ValidateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2011,19 +1932,15 @@ def test_validate_agent( with mock.patch.object(type(client.transport.validate_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult(name="name_value",) - response = client.validate_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2035,7 +1952,7 @@ def test_validate_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2043,7 +1960,6 @@ def test_validate_agent_empty_call(): client.validate_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() @@ -2052,7 +1968,7 @@ async def test_validate_agent_async( transport: str = "grpc_asyncio", request_type=agent.ValidateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2065,18 +1981,15 @@ async def test_validate_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult(name="name_value",) ) - response = await client.validate_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2086,17 +1999,17 @@ async def test_validate_agent_async_from_dict(): def test_validate_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ValidateAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.validate_agent), "__call__") as call: call.return_value = agent.AgentValidationResult() - client.validate_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2111,11 +2024,12 @@ def test_validate_agent_field_headers(): @pytest.mark.asyncio async def test_validate_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ValidateAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2123,7 +2037,6 @@ async def test_validate_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult() ) - await client.validate_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2140,7 +2053,7 @@ def test_get_agent_validation_result( transport: str = "grpc", request_type=agent.GetAgentValidationResultRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2153,19 +2066,15 @@ def test_get_agent_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult(name="name_value",) - response = client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2177,7 +2086,7 @@ def test_get_agent_validation_result_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2187,7 +2096,6 @@ def test_get_agent_validation_result_empty_call(): client.get_agent_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() @@ -2196,7 +2104,7 @@ async def test_get_agent_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentValidationResultRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2211,18 +2119,15 @@ async def test_get_agent_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult(name="name_value",) ) - response = await client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2232,11 +2137,12 @@ async def test_get_agent_validation_result_async_from_dict(): def test_get_agent_validation_result_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.GetAgentValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2244,7 +2150,6 @@ def test_get_agent_validation_result_field_headers(): type(client.transport.get_agent_validation_result), "__call__" ) as call: call.return_value = agent.AgentValidationResult() - client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2259,11 +2164,12 @@ def test_get_agent_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_agent_validation_result_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.GetAgentValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2273,7 +2179,6 @@ async def test_get_agent_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult() ) - await client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2287,7 +2192,7 @@ async def test_get_agent_validation_result_field_headers_async(): def test_get_agent_validation_result_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2295,7 +2200,6 @@ def test_get_agent_validation_result_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent_validation_result(name="name_value",) @@ -2304,12 +2208,11 @@ def test_get_agent_validation_result_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_agent_validation_result_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2321,7 +2224,7 @@ def test_get_agent_validation_result_flattened_error(): @pytest.mark.asyncio async def test_get_agent_validation_result_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2341,13 +2244,12 @@ async def test_get_agent_validation_result_flattened_async(): # 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_agent_validation_result_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2360,16 +2262,16 @@ async def test_get_agent_validation_result_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2379,7 +2281,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2390,7 +2292,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AgentsClient(transport=transport) assert client.transport is transport @@ -2399,13 +2301,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AgentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2417,23 +2319,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AgentsGrpcTransport,) def test_agents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2445,7 +2347,7 @@ def test_agents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2471,15 +2373,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2495,19 +2422,36 @@ def test_agents_base_transport_with_credentials_file(): def test_agents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2518,14 +2462,38 @@ def test_agents_auth_adc(): ) -def test_agents_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AgentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2535,12 +2503,123 @@ def test_agents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_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,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport], ) def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2582,7 +2661,7 @@ def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_agents_host_no_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2592,7 +2671,7 @@ def test_agents_host_no_port(): def test_agents_host_with_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2643,9 +2722,9 @@ def test_agents_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2724,7 +2803,7 @@ def test_agents_transport_channel_mtls_with_adc(transport_class): def test_agents_grpc_lro_client(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2737,7 +2816,7 @@ def test_agents_grpc_lro_client(): def test_agents_grpc_lro_async_client(): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2752,7 +2831,6 @@ def test_agent_path(): project = "squid" location = "clam" agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @@ -2777,7 +2855,6 @@ def test_agent_validation_result_path(): project = "cuttlefish" location = "mussel" agent = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( project=project, location=location, agent=agent, ) @@ -2798,65 +2875,88 @@ def test_parse_agent_validation_result_path(): assert expected == actual -def test_flow_path(): +def test_environment_path(): project = "squid" location = "clam" agent = "whelk" - flow = "octopus" - - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( - project=project, location=location, agent=agent, flow=flow, + environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( + project=project, location=location, agent=agent, environment=environment, ) - actual = AgentsClient.flow_path(project, location, agent, flow) + actual = AgentsClient.environment_path(project, location, agent, environment) assert expected == actual -def test_parse_flow_path(): +def test_parse_environment_path(): expected = { "project": "oyster", "location": "nudibranch", "agent": "cuttlefish", - "flow": "mussel", + "environment": "mussel", } - path = AgentsClient.flow_path(**expected) + path = AgentsClient.environment_path(**expected) # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_path(path) + actual = AgentsClient.parse_environment_path(path) assert expected == actual -def test_flow_validation_result_path(): +def test_flow_path(): project = "winkle" location = "nautilus" agent = "scallop" flow = "abalone" - - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + actual = AgentsClient.flow_path(project, location, agent, flow) assert expected == actual -def test_parse_flow_validation_result_path(): +def test_parse_flow_path(): expected = { "project": "squid", "location": "clam", "agent": "whelk", "flow": "octopus", } - path = AgentsClient.flow_validation_result_path(**expected) + path = AgentsClient.flow_path(**expected) # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_validation_result_path(path) + actual = AgentsClient.parse_flow_path(path) assert expected == actual -def test_security_settings_path(): +def test_flow_validation_result_path(): project = "oyster" location = "nudibranch" - security_settings = "cuttlefish" + agent = "cuttlefish" + flow = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( + project=project, location=location, agent=agent, flow=flow, + ) + actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "flow": "abalone", + } + path = AgentsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @@ -2866,9 +2966,9 @@ def test_security_settings_path(): def test_parse_security_settings_path(): expected = { - "project": "mussel", - "location": "winkle", - "security_settings": "nautilus", + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", } path = AgentsClient.security_settings_path(**expected) @@ -2878,8 +2978,7 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): - billing_account = "scallop" - + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2889,7 +2988,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "mussel", } path = AgentsClient.common_billing_account_path(**expected) @@ -2899,8 +2998,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2908,7 +3006,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "nautilus", } path = AgentsClient.common_folder_path(**expected) @@ -2918,8 +3016,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2927,7 +3024,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "abalone", } path = AgentsClient.common_organization_path(**expected) @@ -2937,8 +3034,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2946,7 +3042,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "clam", } path = AgentsClient.common_project_path(**expected) @@ -2956,9 +3052,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2968,8 +3063,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "oyster", + "location": "nudibranch", } path = AgentsClient.common_location_path(**expected) @@ -2985,7 +3080,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AgentsTransport, "_prep_wrapped_messages" ) as prep: client = AgentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2994,6 +3089,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AgentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py b/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py index 81805ac9..b2d6e0f3 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.entity_types import EntityTypesAsyncClient 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +114,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +129,7 @@ def test_entity_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -151,7 +180,7 @@ def test_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -435,7 +464,7 @@ def test_list_entity_types( transport: str = "grpc", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -450,19 +479,15 @@ def test_list_entity_types( call.return_value = entity_type.ListEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -474,7 +499,7 @@ def test_list_entity_types_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -484,7 +509,6 @@ def test_list_entity_types_empty_call(): client.list_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() @@ -493,7 +517,7 @@ async def test_list_entity_types_async( transport: str = "grpc_asyncio", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -510,18 +534,15 @@ async def test_list_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -531,11 +552,12 @@ async def test_list_entity_types_async_from_dict(): def test_list_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ def test_list_entity_types_field_headers(): type(client.transport.list_entity_types), "__call__" ) as call: call.return_value = entity_type.ListEntityTypesResponse() - client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -558,11 +579,12 @@ def test_list_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -572,7 +594,6 @@ async def test_list_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.ListEntityTypesResponse() ) - await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -586,7 +607,7 @@ async def test_list_entity_types_field_headers_async(): def test_list_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -594,7 +615,6 @@ def test_list_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_entity_types(parent="parent_value",) @@ -603,12 +623,11 @@ def test_list_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -620,7 +639,7 @@ def test_list_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -640,13 +659,12 @@ async def test_list_entity_types_flattened_async(): # 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_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -657,7 +675,7 @@ async def test_list_entity_types_flattened_error_async(): def test_list_entity_types_pager(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,7 +717,7 @@ def test_list_entity_types_pager(): def test_list_entity_types_pages(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -733,7 +751,7 @@ def test_list_entity_types_pages(): @pytest.mark.asyncio async def test_list_entity_types_async_pager(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -774,7 +792,7 @@ async def test_list_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_entity_types_async_pages(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -814,7 +832,7 @@ def test_get_entity_type( transport: str = "grpc", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -832,32 +850,23 @@ def test_get_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -869,7 +878,7 @@ def test_get_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -877,7 +886,6 @@ def test_get_entity_type_empty_call(): client.get_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() @@ -886,7 +894,7 @@ async def test_get_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -906,31 +914,23 @@ async def test_get_entity_type_async( redact=True, ) ) - response = await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -940,17 +940,17 @@ async def test_get_entity_type_async_from_dict(): def test_get_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: call.return_value = entity_type.EntityType() - client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -965,11 +965,12 @@ def test_get_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -977,7 +978,6 @@ async def test_get_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.EntityType() ) - await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -991,13 +991,12 @@ async def test_get_entity_type_field_headers_async(): def test_get_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_entity_type(name="name_value",) @@ -1006,12 +1005,11 @@ def test_get_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1023,7 +1021,7 @@ def test_get_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: @@ -1041,13 +1039,12 @@ async def test_get_entity_type_flattened_async(): # 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_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1061,7 +1058,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcdc_entity_type.CreateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1081,32 +1078,23 @@ def test_create_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1118,7 +1106,7 @@ def test_create_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1128,7 +1116,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() @@ -1138,7 +1125,7 @@ async def test_create_entity_type_async( request_type=gcdc_entity_type.CreateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1160,31 +1147,23 @@ async def test_create_entity_type_async( redact=True, ) ) - response = await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1194,11 +1173,12 @@ async def test_create_entity_type_async_from_dict(): def test_create_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = gcdc_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1206,7 +1186,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcdc_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1221,11 +1200,12 @@ def test_create_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = gcdc_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1235,7 +1215,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1249,7 +1228,7 @@ async def test_create_entity_type_field_headers_async(): def test_create_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1257,7 +1236,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_entity_type( @@ -1269,14 +1247,12 @@ def test_create_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") def test_create_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1290,7 +1266,7 @@ def test_create_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,15 +1289,13 @@ async def test_create_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") @pytest.mark.asyncio async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1311,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcdc_entity_type.UpdateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1357,32 +1331,23 @@ def test_update_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1394,7 +1359,7 @@ def test_update_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1404,7 +1369,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() @@ -1414,7 +1378,7 @@ async def test_update_entity_type_async( request_type=gcdc_entity_type.UpdateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1436,31 +1400,23 @@ async def test_update_entity_type_async( redact=True, ) ) - response = await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1470,11 +1426,12 @@ async def test_update_entity_type_async_from_dict(): def test_update_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = gcdc_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1482,7 +1439,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcdc_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1499,11 +1455,12 @@ def test_update_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = gcdc_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1513,7 +1470,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1529,7 +1485,7 @@ async def test_update_entity_type_field_headers_async(): def test_update_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1537,26 +1493,23 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_entity_type( entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1564,13 +1517,13 @@ def test_update_entity_type_flattened_error(): client.update_entity_type( gcdc_entity_type.UpdateEntityTypeRequest(), entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1586,22 +1539,20 @@ async def test_update_entity_type_flattened_async(): # using the keyword arguments to the method. response = await client.update_entity_type( entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1609,7 +1560,7 @@ async def test_update_entity_type_flattened_error_async(): await client.update_entity_type( gcdc_entity_type.UpdateEntityTypeRequest(), entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1617,7 +1568,7 @@ def test_delete_entity_type( transport: str = "grpc", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1630,13 +1581,11 @@ def test_delete_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1651,7 +1600,7 @@ def test_delete_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1661,7 +1610,6 @@ def test_delete_entity_type_empty_call(): client.delete_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() @@ -1670,7 +1618,7 @@ async def test_delete_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1683,13 +1631,11 @@ async def test_delete_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1702,11 +1648,12 @@ async def test_delete_entity_type_async_from_dict(): def test_delete_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1714,7 +1661,6 @@ def test_delete_entity_type_field_headers(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = None - client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1729,11 +1675,12 @@ def test_delete_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1741,7 +1688,6 @@ async def test_delete_entity_type_field_headers_async(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1755,7 +1701,7 @@ async def test_delete_entity_type_field_headers_async(): def test_delete_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1763,7 +1709,6 @@ def test_delete_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_entity_type(name="name_value",) @@ -1772,12 +1717,11 @@ def test_delete_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1789,7 +1733,7 @@ def test_delete_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1807,13 +1751,12 @@ async def test_delete_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1826,16 +1769,16 @@ async def test_delete_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -1845,7 +1788,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -1856,7 +1799,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EntityTypesClient(transport=transport) assert client.transport is transport @@ -1865,13 +1808,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1883,23 +1826,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EntityTypesGrpcTransport,) def test_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1911,7 +1854,7 @@ def test_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1928,15 +1871,40 @@ def test_entity_types_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1952,19 +1920,36 @@ def test_entity_types_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1975,14 +1960,38 @@ def test_entity_types_auth_adc(): ) -def test_entity_types_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1992,12 +2001,127 @@ def test_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_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,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport], ) def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2039,7 +2163,7 @@ def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class def test_entity_types_host_no_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2049,7 +2173,7 @@ def test_entity_types_host_no_port(): def test_entity_types_host_with_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2100,9 +2224,9 @@ def test_entity_types_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2184,7 +2308,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -2208,7 +2331,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2229,7 +2351,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2248,7 +2369,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2267,7 +2387,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -2287,7 +2406,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2314,7 +2432,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2323,6 +2441,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_environments.py b/tests/unit/gapic/dialogflowcx_v3/test_environments.py index b8e4a510..fd0cb977 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_environments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.environments import EnvironmentsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -106,7 +135,7 @@ def test_environments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -157,7 +186,7 @@ def test_environments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EnvironmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -441,7 +470,7 @@ def test_list_environments( transport: str = "grpc", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -456,19 +485,15 @@ def test_list_environments( call.return_value = environment.ListEnvironmentsResponse( next_page_token="next_page_token_value", ) - response = client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == "next_page_token_value" @@ -480,7 +505,7 @@ def test_list_environments_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -490,7 +515,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -499,7 +523,7 @@ async def test_list_environments_async( transport: str = "grpc_asyncio", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -516,18 +540,15 @@ async def test_list_environments_async( next_page_token="next_page_token_value", ) ) - response = await client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -537,11 +558,12 @@ async def test_list_environments_async_from_dict(): def test_list_environments_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -549,7 +571,6 @@ def test_list_environments_field_headers(): type(client.transport.list_environments), "__call__" ) as call: call.return_value = environment.ListEnvironmentsResponse() - client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -564,11 +585,12 @@ def test_list_environments_field_headers(): @pytest.mark.asyncio async def test_list_environments_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -578,7 +600,6 @@ async def test_list_environments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.ListEnvironmentsResponse() ) - await client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -592,7 +613,7 @@ async def test_list_environments_field_headers_async(): def test_list_environments_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -600,7 +621,6 @@ def test_list_environments_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = environment.ListEnvironmentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_environments(parent="parent_value",) @@ -609,12 +629,11 @@ def test_list_environments_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_environments_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -626,7 +645,7 @@ def test_list_environments_flattened_error(): @pytest.mark.asyncio async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -646,13 +665,12 @@ async def test_list_environments_flattened_async(): # 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_environments_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -663,7 +681,7 @@ async def test_list_environments_flattened_error_async(): def test_list_environments_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,7 +723,7 @@ def test_list_environments_pager(): def test_list_environments_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -739,7 +757,7 @@ def test_list_environments_pages(): @pytest.mark.asyncio async def test_list_environments_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -780,7 +798,7 @@ async def test_list_environments_async_pager(): @pytest.mark.asyncio async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -820,7 +838,7 @@ def test_get_environment( transport: str = "grpc", request_type=environment.GetEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -835,23 +853,17 @@ def test_get_environment( display_name="display_name_value", description="description_value", ) - response = client.get_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -863,7 +875,7 @@ def test_get_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -871,7 +883,6 @@ def test_get_environment_empty_call(): client.get_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() @@ -880,7 +891,7 @@ async def test_get_environment_async( transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -897,22 +908,17 @@ async def test_get_environment_async( description="description_value", ) ) - response = await client.get_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() # Establish that the response is the type that we expect. assert isinstance(response, environment.Environment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -922,17 +928,17 @@ async def test_get_environment_async_from_dict(): def test_get_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.GetEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: call.return_value = environment.Environment() - client.get_environment(request) # Establish that the underlying gRPC stub method was called. @@ -947,11 +953,12 @@ def test_get_environment_field_headers(): @pytest.mark.asyncio async def test_get_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.GetEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -959,7 +966,6 @@ async def test_get_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.Environment() ) - await client.get_environment(request) # Establish that the underlying gRPC stub method was called. @@ -973,13 +979,12 @@ async def test_get_environment_field_headers_async(): def test_get_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = environment.Environment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_environment(name="name_value",) @@ -988,12 +993,11 @@ def test_get_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1005,7 +1009,7 @@ def test_get_environment_flattened_error(): @pytest.mark.asyncio async def test_get_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: @@ -1023,13 +1027,12 @@ async def test_get_environment_flattened_async(): # 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1043,7 +1046,7 @@ def test_create_environment( transport: str = "grpc", request_type=gcdc_environment.CreateEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1056,13 +1059,11 @@ def test_create_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1077,7 +1078,7 @@ def test_create_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1087,7 +1088,6 @@ def test_create_environment_empty_call(): client.create_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() @@ -1097,7 +1097,7 @@ async def test_create_environment_async( request_type=gcdc_environment.CreateEnvironmentRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1112,13 +1112,11 @@ async def test_create_environment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1131,11 +1129,12 @@ async def test_create_environment_async_from_dict(): def test_create_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.CreateEnvironmentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1143,7 +1142,6 @@ def test_create_environment_field_headers(): type(client.transport.create_environment), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1158,11 +1156,12 @@ def test_create_environment_field_headers(): @pytest.mark.asyncio async def test_create_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.CreateEnvironmentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1172,7 +1171,6 @@ async def test_create_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1186,7 +1184,7 @@ async def test_create_environment_field_headers_async(): def test_create_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1194,7 +1192,6 @@ def test_create_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_environment( @@ -1206,14 +1203,12 @@ def test_create_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].environment == gcdc_environment.Environment(name="name_value") def test_create_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1227,7 +1222,7 @@ def test_create_environment_flattened_error(): @pytest.mark.asyncio async def test_create_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1250,15 +1245,13 @@ async def test_create_environment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].environment == gcdc_environment.Environment(name="name_value") @pytest.mark.asyncio async def test_create_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1274,7 +1267,7 @@ def test_update_environment( transport: str = "grpc", request_type=gcdc_environment.UpdateEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1287,13 +1280,11 @@ def test_update_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1308,7 +1299,7 @@ def test_update_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1318,7 +1309,6 @@ def test_update_environment_empty_call(): client.update_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() @@ -1328,7 +1318,7 @@ async def test_update_environment_async( request_type=gcdc_environment.UpdateEnvironmentRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1343,13 +1333,11 @@ async def test_update_environment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1362,11 +1350,12 @@ async def test_update_environment_async_from_dict(): def test_update_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.UpdateEnvironmentRequest() + request.environment.name = "environment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1374,7 +1363,6 @@ def test_update_environment_field_headers(): type(client.transport.update_environment), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1391,11 +1379,12 @@ def test_update_environment_field_headers(): @pytest.mark.asyncio async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.UpdateEnvironmentRequest() + request.environment.name = "environment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1405,7 +1394,6 @@ async def test_update_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1421,7 +1409,7 @@ async def test_update_environment_field_headers_async(): def test_update_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1429,26 +1417,23 @@ def test_update_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_environment( environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].environment == gcdc_environment.Environment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1456,13 +1441,13 @@ def test_update_environment_flattened_error(): client.update_environment( gcdc_environment.UpdateEnvironmentRequest(), environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1478,22 +1463,20 @@ async def test_update_environment_flattened_async(): # using the keyword arguments to the method. response = await client.update_environment( environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].environment == gcdc_environment.Environment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1501,7 +1484,7 @@ async def test_update_environment_flattened_error_async(): await client.update_environment( gcdc_environment.UpdateEnvironmentRequest(), environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1509,7 +1492,7 @@ def test_delete_environment( transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1522,13 +1505,11 @@ def test_delete_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1543,7 +1524,7 @@ def test_delete_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1553,7 +1534,6 @@ def test_delete_environment_empty_call(): client.delete_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() @@ -1562,7 +1542,7 @@ async def test_delete_environment_async( transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1575,13 +1555,11 @@ async def test_delete_environment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1594,11 +1572,12 @@ async def test_delete_environment_async_from_dict(): def test_delete_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.DeleteEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1606,7 +1585,6 @@ def test_delete_environment_field_headers(): type(client.transport.delete_environment), "__call__" ) as call: call.return_value = None - client.delete_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1621,11 +1599,12 @@ def test_delete_environment_field_headers(): @pytest.mark.asyncio async def test_delete_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.DeleteEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1633,7 +1612,6 @@ async def test_delete_environment_field_headers_async(): type(client.transport.delete_environment), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1647,7 +1625,7 @@ async def test_delete_environment_field_headers_async(): def test_delete_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1655,7 +1633,6 @@ def test_delete_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_environment(name="name_value",) @@ -1664,12 +1641,11 @@ def test_delete_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1681,7 +1657,7 @@ def test_delete_environment_flattened_error(): @pytest.mark.asyncio async def test_delete_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1699,13 +1675,12 @@ async def test_delete_environment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1719,7 +1694,7 @@ def test_lookup_environment_history( transport: str = "grpc", request_type=environment.LookupEnvironmentHistoryRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1734,19 +1709,15 @@ def test_lookup_environment_history( call.return_value = environment.LookupEnvironmentHistoryResponse( next_page_token="next_page_token_value", ) - response = client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryPager) - assert response.next_page_token == "next_page_token_value" @@ -1758,7 +1729,7 @@ def test_lookup_environment_history_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1768,7 +1739,6 @@ def test_lookup_environment_history_empty_call(): client.lookup_environment_history() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() @@ -1778,7 +1748,7 @@ async def test_lookup_environment_history_async( request_type=environment.LookupEnvironmentHistoryRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1795,18 +1765,15 @@ async def test_lookup_environment_history_async( next_page_token="next_page_token_value", ) ) - response = await client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1816,11 +1783,12 @@ async def test_lookup_environment_history_async_from_dict(): def test_lookup_environment_history_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.LookupEnvironmentHistoryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1828,7 +1796,6 @@ def test_lookup_environment_history_field_headers(): type(client.transport.lookup_environment_history), "__call__" ) as call: call.return_value = environment.LookupEnvironmentHistoryResponse() - client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. @@ -1843,11 +1810,12 @@ def test_lookup_environment_history_field_headers(): @pytest.mark.asyncio async def test_lookup_environment_history_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.LookupEnvironmentHistoryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1857,7 +1825,6 @@ async def test_lookup_environment_history_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.LookupEnvironmentHistoryResponse() ) - await client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. @@ -1871,7 +1838,7 @@ async def test_lookup_environment_history_field_headers_async(): def test_lookup_environment_history_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1879,7 +1846,6 @@ def test_lookup_environment_history_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = environment.LookupEnvironmentHistoryResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.lookup_environment_history(name="name_value",) @@ -1888,12 +1854,11 @@ def test_lookup_environment_history_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_lookup_environment_history_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1905,7 +1870,7 @@ def test_lookup_environment_history_flattened_error(): @pytest.mark.asyncio async def test_lookup_environment_history_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1925,13 +1890,12 @@ async def test_lookup_environment_history_flattened_async(): # 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_lookup_environment_history_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1942,7 +1906,7 @@ async def test_lookup_environment_history_flattened_error_async(): def test_lookup_environment_history_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1984,7 +1948,7 @@ def test_lookup_environment_history_pager(): def test_lookup_environment_history_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2018,7 +1982,7 @@ def test_lookup_environment_history_pages(): @pytest.mark.asyncio async def test_lookup_environment_history_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2059,7 +2023,7 @@ async def test_lookup_environment_history_async_pager(): @pytest.mark.asyncio async def test_lookup_environment_history_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2098,16 +2062,16 @@ async def test_lookup_environment_history_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( @@ -2117,7 +2081,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( @@ -2128,7 +2092,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EnvironmentsClient(transport=transport) assert client.transport is transport @@ -2137,13 +2101,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2158,23 +2122,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) def test_environments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2186,7 +2150,7 @@ def test_environments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2209,15 +2173,40 @@ 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( - auth, "load_credentials_from_file" + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EnvironmentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2233,19 +2222,36 @@ def test_environments_base_transport_with_credentials_file(): def test_environments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EnvironmentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2256,14 +2262,44 @@ def test_environments_auth_adc(): ) -def test_environments_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2273,12 +2309,127 @@ def test_environments_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_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,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], ) def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2320,7 +2471,7 @@ def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class def test_environments_host_no_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2330,7 +2481,7 @@ def test_environments_host_no_port(): def test_environments_host_with_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2381,9 +2532,9 @@ def test_environments_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2462,7 +2613,7 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environments_grpc_lro_client(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2475,7 +2626,7 @@ def test_environments_grpc_lro_client(): def test_environments_grpc_lro_async_client(): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2491,7 +2642,6 @@ def test_environment_path(): location = "clam" agent = "whelk" environment = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @@ -2519,7 +2669,6 @@ def test_version_path(): agent = "scallop" flow = "abalone" version = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2544,7 +2693,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2565,7 +2713,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -2584,7 +2731,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -2603,7 +2749,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -2623,7 +2768,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2650,7 +2794,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EnvironmentsTransport, "_prep_wrapped_messages" ) as prep: client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2659,6 +2803,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EnvironmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py index 5f2f59aa..c27de0d0 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_experiments.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_experiments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,24 +23,54 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsAsyncClient from google.cloud.dialogflowcx_v3.services.experiments import ExperimentsClient from google.cloud.dialogflowcx_v3.services.experiments import pagers from google.cloud.dialogflowcx_v3.services.experiments import transports +from google.cloud.dialogflowcx_v3.services.experiments.transports.base import ( + _API_CORE_VERSION, +) +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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient,]) def test_experiments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_experiments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient,]) def test_experiments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -153,7 +182,7 @@ def test_experiments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ExperimentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -437,7 +466,7 @@ def test_list_experiments( transport: str = "grpc", request_type=experiment.ListExperimentsRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -450,19 +479,15 @@ def test_list_experiments( call.return_value = experiment.ListExperimentsResponse( next_page_token="next_page_token_value", ) - response = client.list_experiments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsPager) - assert response.next_page_token == "next_page_token_value" @@ -474,7 +499,7 @@ def test_list_experiments_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -482,7 +507,6 @@ def test_list_experiments_empty_call(): client.list_experiments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() @@ -491,7 +515,7 @@ async def test_list_experiments_async( transport: str = "grpc_asyncio", request_type=experiment.ListExperimentsRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -504,18 +528,15 @@ async def test_list_experiments_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.ListExperimentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_experiments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListExperimentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -525,17 +546,17 @@ async def test_list_experiments_async_from_dict(): def test_list_experiments_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: call.return_value = experiment.ListExperimentsResponse() - client.list_experiments(request) # Establish that the underlying gRPC stub method was called. @@ -550,11 +571,12 @@ def test_list_experiments_field_headers(): @pytest.mark.asyncio async def test_list_experiments_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -562,7 +584,6 @@ async def test_list_experiments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.ListExperimentsResponse() ) - await client.list_experiments(request) # Establish that the underlying gRPC stub method was called. @@ -576,13 +597,12 @@ async def test_list_experiments_field_headers_async(): def test_list_experiments_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.ListExperimentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_experiments(parent="parent_value",) @@ -591,12 +611,11 @@ def test_list_experiments_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_experiments_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -608,7 +627,7 @@ def test_list_experiments_flattened_error(): @pytest.mark.asyncio async def test_list_experiments_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -626,13 +645,12 @@ async def test_list_experiments_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_experiments_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -643,7 +661,7 @@ async def test_list_experiments_flattened_error_async(): def test_list_experiments_pager(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -681,7 +699,7 @@ def test_list_experiments_pager(): def test_list_experiments_pages(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -711,7 +729,7 @@ def test_list_experiments_pages(): @pytest.mark.asyncio async def test_list_experiments_async_pager(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -748,7 +766,7 @@ async def test_list_experiments_async_pager(): @pytest.mark.asyncio async def test_list_experiments_async_pages(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -784,7 +802,7 @@ def test_get_experiment( transport: str = "grpc", request_type=experiment.GetExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -800,25 +818,18 @@ def test_get_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.get_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -830,7 +841,7 @@ def test_get_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -838,7 +849,6 @@ def test_get_experiment_empty_call(): client.get_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() @@ -847,7 +857,7 @@ async def test_get_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.GetExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -865,24 +875,18 @@ async def test_get_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.get_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -892,17 +896,17 @@ async def test_get_experiment_async_from_dict(): def test_get_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.GetExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.get_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -917,11 +921,12 @@ def test_get_experiment_field_headers(): @pytest.mark.asyncio async def test_get_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.GetExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -929,7 +934,6 @@ async def test_get_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.get_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -943,13 +947,12 @@ async def test_get_experiment_field_headers_async(): def test_get_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_experiment(name="name_value",) @@ -958,12 +961,11 @@ def test_get_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -975,7 +977,7 @@ def test_get_experiment_flattened_error(): @pytest.mark.asyncio async def test_get_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: @@ -993,13 +995,12 @@ async def test_get_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1013,7 +1014,7 @@ def test_create_experiment( transport: str = "grpc", request_type=gcdc_experiment.CreateExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1031,25 +1032,18 @@ def test_create_experiment( description="description_value", state=gcdc_experiment.Experiment.State.DRAFT, ) - response = client.create_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1061,7 +1055,7 @@ def test_create_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1071,7 +1065,6 @@ def test_create_experiment_empty_call(): client.create_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() @@ -1081,7 +1074,7 @@ async def test_create_experiment_async( request_type=gcdc_experiment.CreateExperimentRequest, ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1101,24 +1094,18 @@ async def test_create_experiment_async( state=gcdc_experiment.Experiment.State.DRAFT, ) ) - response = await client.create_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1128,11 +1115,12 @@ async def test_create_experiment_async_from_dict(): def test_create_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1140,7 +1128,6 @@ def test_create_experiment_field_headers(): type(client.transport.create_experiment), "__call__" ) as call: call.return_value = gcdc_experiment.Experiment() - client.create_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1155,11 +1142,12 @@ def test_create_experiment_field_headers(): @pytest.mark.asyncio async def test_create_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1169,7 +1157,6 @@ async def test_create_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_experiment.Experiment() ) - await client.create_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1183,7 +1170,7 @@ async def test_create_experiment_field_headers_async(): def test_create_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1191,7 +1178,6 @@ def test_create_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_experiment( @@ -1203,14 +1189,12 @@ def test_create_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") def test_create_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1224,7 +1208,7 @@ def test_create_experiment_flattened_error(): @pytest.mark.asyncio async def test_create_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1247,15 +1231,13 @@ async def test_create_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") @pytest.mark.asyncio async def test_create_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1271,7 +1253,7 @@ def test_update_experiment( transport: str = "grpc", request_type=gcdc_experiment.UpdateExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1289,25 +1271,18 @@ def test_update_experiment( description="description_value", state=gcdc_experiment.Experiment.State.DRAFT, ) - response = client.update_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1319,7 +1294,7 @@ def test_update_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1329,7 +1304,6 @@ def test_update_experiment_empty_call(): client.update_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() @@ -1339,7 +1313,7 @@ async def test_update_experiment_async( request_type=gcdc_experiment.UpdateExperimentRequest, ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1359,24 +1333,18 @@ async def test_update_experiment_async( state=gcdc_experiment.Experiment.State.DRAFT, ) ) - response = await client.update_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1386,11 +1354,12 @@ async def test_update_experiment_async_from_dict(): def test_update_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1398,7 +1367,6 @@ def test_update_experiment_field_headers(): type(client.transport.update_experiment), "__call__" ) as call: call.return_value = gcdc_experiment.Experiment() - client.update_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1415,11 +1383,12 @@ def test_update_experiment_field_headers(): @pytest.mark.asyncio async def test_update_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1429,7 +1398,6 @@ async def test_update_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_experiment.Experiment() ) - await client.update_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1445,7 +1413,7 @@ async def test_update_experiment_field_headers_async(): def test_update_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1453,26 +1421,23 @@ def test_update_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_experiment( experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1480,13 +1445,13 @@ def test_update_experiment_flattened_error(): client.update_experiment( gcdc_experiment.UpdateExperimentRequest(), experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1502,22 +1467,20 @@ async def test_update_experiment_flattened_async(): # using the keyword arguments to the method. response = await client.update_experiment( experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1525,7 +1488,7 @@ async def test_update_experiment_flattened_error_async(): await client.update_experiment( gcdc_experiment.UpdateExperimentRequest(), experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1533,7 +1496,7 @@ def test_delete_experiment( transport: str = "grpc", request_type=experiment.DeleteExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1546,13 +1509,11 @@ def test_delete_experiment( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() # Establish that the response is the type that we expect. @@ -1567,7 +1528,7 @@ def test_delete_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1577,7 +1538,6 @@ def test_delete_experiment_empty_call(): client.delete_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() @@ -1586,7 +1546,7 @@ async def test_delete_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.DeleteExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1599,13 +1559,11 @@ async def test_delete_experiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() # Establish that the response is the type that we expect. @@ -1618,11 +1576,12 @@ async def test_delete_experiment_async_from_dict(): def test_delete_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.DeleteExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1630,7 +1589,6 @@ def test_delete_experiment_field_headers(): type(client.transport.delete_experiment), "__call__" ) as call: call.return_value = None - client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1645,11 +1603,12 @@ def test_delete_experiment_field_headers(): @pytest.mark.asyncio async def test_delete_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.DeleteExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1657,7 +1616,6 @@ async def test_delete_experiment_field_headers_async(): type(client.transport.delete_experiment), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1671,7 +1629,7 @@ async def test_delete_experiment_field_headers_async(): def test_delete_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1679,7 +1637,6 @@ def test_delete_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_experiment(name="name_value",) @@ -1688,12 +1645,11 @@ def test_delete_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1705,7 +1661,7 @@ def test_delete_experiment_flattened_error(): @pytest.mark.asyncio async def test_delete_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1723,13 +1679,12 @@ async def test_delete_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1743,7 +1698,7 @@ def test_start_experiment( transport: str = "grpc", request_type=experiment.StartExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1759,25 +1714,18 @@ def test_start_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.start_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -1789,7 +1737,7 @@ def test_start_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1797,7 +1745,6 @@ def test_start_experiment_empty_call(): client.start_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() @@ -1806,7 +1753,7 @@ async def test_start_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.StartExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1824,24 +1771,18 @@ async def test_start_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.start_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -1851,17 +1792,17 @@ async def test_start_experiment_async_from_dict(): def test_start_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.StartExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.start_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1876,11 +1817,12 @@ def test_start_experiment_field_headers(): @pytest.mark.asyncio async def test_start_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.StartExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1888,7 +1830,6 @@ async def test_start_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.start_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1902,13 +1843,12 @@ async def test_start_experiment_field_headers_async(): def test_start_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.start_experiment(name="name_value",) @@ -1917,12 +1857,11 @@ def test_start_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_start_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1934,7 +1873,7 @@ def test_start_experiment_flattened_error(): @pytest.mark.asyncio async def test_start_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: @@ -1952,13 +1891,12 @@ async def test_start_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_start_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1972,7 +1910,7 @@ def test_stop_experiment( transport: str = "grpc", request_type=experiment.StopExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1988,25 +1926,18 @@ def test_stop_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -2018,7 +1949,7 @@ def test_stop_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2026,7 +1957,6 @@ def test_stop_experiment_empty_call(): client.stop_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() @@ -2035,7 +1965,7 @@ async def test_stop_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.StopExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2053,24 +1983,18 @@ async def test_stop_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -2080,17 +2004,17 @@ async def test_stop_experiment_async_from_dict(): def test_stop_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.StopExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -2105,11 +2029,12 @@ def test_stop_experiment_field_headers(): @pytest.mark.asyncio async def test_stop_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.StopExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2117,7 +2042,6 @@ async def test_stop_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -2131,13 +2055,12 @@ async def test_stop_experiment_field_headers_async(): def test_stop_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.stop_experiment(name="name_value",) @@ -2146,12 +2069,11 @@ def test_stop_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_stop_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2163,7 +2085,7 @@ def test_stop_experiment_flattened_error(): @pytest.mark.asyncio async def test_stop_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: @@ -2181,13 +2103,12 @@ async def test_stop_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_stop_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2200,16 +2121,16 @@ async def test_stop_experiment_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( @@ -2219,7 +2140,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( @@ -2230,7 +2151,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ExperimentsClient(transport=transport) assert client.transport is transport @@ -2239,13 +2160,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ExperimentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2257,23 +2178,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ExperimentsGrpcTransport,) def test_experiments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ExperimentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2285,7 +2206,7 @@ def test_experiments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ExperimentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2304,15 +2225,40 @@ def test_experiments_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2328,19 +2274,36 @@ def test_experiments_base_transport_with_credentials_file(): def test_experiments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ExperimentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2351,14 +2314,38 @@ def test_experiments_auth_adc(): ) -def test_experiments_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ExperimentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2368,12 +2355,127 @@ def test_experiments_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_experiments_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,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], ) def test_experiments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2415,7 +2517,7 @@ def test_experiments_grpc_transport_client_cert_source_for_mtls(transport_class) def test_experiments_host_no_port(): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2425,7 +2527,7 @@ def test_experiments_host_no_port(): def test_experiments_host_with_port(): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2476,9 +2578,9 @@ def test_experiments_transport_channel_mtls_with_client_cert_source(transport_cl mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2561,7 +2663,6 @@ def test_experiment_path(): agent = "whelk" environment = "octopus" experiment = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( project=project, location=location, @@ -2596,7 +2697,6 @@ def test_version_path(): agent = "squid" flow = "clam" version = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2621,7 +2721,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2642,7 +2741,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = ExperimentsClient.common_folder_path(folder) assert expected == actual @@ -2661,7 +2759,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = ExperimentsClient.common_organization_path(organization) assert expected == actual @@ -2680,7 +2777,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = ExperimentsClient.common_project_path(project) assert expected == actual @@ -2700,7 +2796,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2727,7 +2822,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ExperimentsTransport, "_prep_wrapped_messages" ) as prep: client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2736,6 +2831,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ExperimentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_flows.py b/tests/unit/gapic/dialogflowcx_v3/test_flows.py index 685cfaff..b29bba23 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_flows.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_flows.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,27 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.flows import FlowsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 @@ -47,9 +52,33 @@ from google.cloud.dialogflowcx_v3.types import validation_message from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [FlowsClient, FlowsAsyncClient,]) def test_flows_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_flows_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [FlowsClient, FlowsAsyncClient,]) def test_flows_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_flows_client_get_transport_class(): def test_flows_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(FlowsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -422,7 +451,7 @@ def test_flows_client_client_options_from_dict(): def test_create_flow(transport: str = "grpc", request_type=gcdc_flow.CreateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -436,25 +465,21 @@ def test_create_flow(transport: str = "grpc", request_type=gcdc_flow.CreateFlowR name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.create_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_create_flow_from_dict(): @@ -465,7 +490,7 @@ def test_create_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -473,7 +498,6 @@ def test_create_flow_empty_call(): client.create_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() @@ -482,7 +506,7 @@ async def test_create_flow_async( transport: str = "grpc_asyncio", request_type=gcdc_flow.CreateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,25 +521,22 @@ async def test_create_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.create_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -524,17 +545,17 @@ async def test_create_flow_async_from_dict(): def test_create_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = gcdc_flow.CreateFlowRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: call.return_value = gcdc_flow.Flow() - client.create_flow(request) # Establish that the underlying gRPC stub method was called. @@ -549,17 +570,17 @@ def test_create_flow_field_headers(): @pytest.mark.asyncio async def test_create_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = gcdc_flow.CreateFlowRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.create_flow(request) # Establish that the underlying gRPC stub method was called. @@ -573,13 +594,12 @@ async def test_create_flow_field_headers_async(): def test_create_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_flow( @@ -590,14 +610,12 @@ def test_create_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].flow == gcdc_flow.Flow(name="name_value") def test_create_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -611,7 +629,7 @@ def test_create_flow_flattened_error(): @pytest.mark.asyncio async def test_create_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: @@ -629,15 +647,13 @@ async def test_create_flow_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].flow == gcdc_flow.Flow(name="name_value") @pytest.mark.asyncio async def test_create_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -651,7 +667,7 @@ async def test_create_flow_flattened_error_async(): def test_delete_flow(transport: str = "grpc", request_type=flow.DeleteFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -662,13 +678,11 @@ def test_delete_flow(transport: str = "grpc", request_type=flow.DeleteFlowReques with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() # Establish that the response is the type that we expect. @@ -683,7 +697,7 @@ def test_delete_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,7 +705,6 @@ def test_delete_flow_empty_call(): client.delete_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() @@ -700,7 +713,7 @@ async def test_delete_flow_async( transport: str = "grpc_asyncio", request_type=flow.DeleteFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -711,13 +724,11 @@ async def test_delete_flow_async( with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() # Establish that the response is the type that we expect. @@ -730,17 +741,17 @@ async def test_delete_flow_async_from_dict(): def test_delete_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.DeleteFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: call.return_value = None - client.delete_flow(request) # Establish that the underlying gRPC stub method was called. @@ -755,17 +766,17 @@ def test_delete_flow_field_headers(): @pytest.mark.asyncio async def test_delete_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.DeleteFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_flow(request) # Establish that the underlying gRPC stub method was called. @@ -779,13 +790,12 @@ async def test_delete_flow_field_headers_async(): def test_delete_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_flow(name="name_value",) @@ -794,12 +804,11 @@ def test_delete_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -811,7 +820,7 @@ def test_delete_flow_flattened_error(): @pytest.mark.asyncio async def test_delete_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: @@ -827,13 +836,12 @@ async def test_delete_flow_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -845,7 +853,7 @@ async def test_delete_flow_flattened_error_async(): def test_list_flows(transport: str = "grpc", request_type=flow.ListFlowsRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -858,19 +866,15 @@ def test_list_flows(transport: str = "grpc", request_type=flow.ListFlowsRequest) call.return_value = flow.ListFlowsResponse( next_page_token="next_page_token_value", ) - response = client.list_flows(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsPager) - assert response.next_page_token == "next_page_token_value" @@ -882,7 +886,7 @@ def test_list_flows_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 = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -890,7 +894,6 @@ def test_list_flows_empty_call(): client.list_flows() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() @@ -899,7 +902,7 @@ async def test_list_flows_async( transport: str = "grpc_asyncio", request_type=flow.ListFlowsRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -912,18 +915,15 @@ async def test_list_flows_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.ListFlowsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_flows(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFlowsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -933,17 +933,17 @@ async def test_list_flows_async_from_dict(): def test_list_flows_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.ListFlowsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: call.return_value = flow.ListFlowsResponse() - client.list_flows(request) # Establish that the underlying gRPC stub method was called. @@ -958,11 +958,12 @@ def test_list_flows_field_headers(): @pytest.mark.asyncio async def test_list_flows_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.ListFlowsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -970,7 +971,6 @@ async def test_list_flows_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.ListFlowsResponse() ) - await client.list_flows(request) # Establish that the underlying gRPC stub method was called. @@ -984,13 +984,12 @@ async def test_list_flows_field_headers_async(): def test_list_flows_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.ListFlowsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_flows(parent="parent_value",) @@ -999,12 +998,11 @@ def test_list_flows_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_flows_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1016,7 +1014,7 @@ def test_list_flows_flattened_error(): @pytest.mark.asyncio async def test_list_flows_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1034,13 +1032,12 @@ async def test_list_flows_flattened_async(): # 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_flows_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1051,7 +1048,7 @@ async def test_list_flows_flattened_error_async(): def test_list_flows_pager(): - client = FlowsClient(credentials=credentials.AnonymousCredentials,) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1080,7 +1077,7 @@ def test_list_flows_pager(): def test_list_flows_pages(): - client = FlowsClient(credentials=credentials.AnonymousCredentials,) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1101,7 +1098,7 @@ def test_list_flows_pages(): @pytest.mark.asyncio async def test_list_flows_async_pager(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1129,7 +1126,7 @@ async def test_list_flows_async_pager(): @pytest.mark.asyncio async def test_list_flows_async_pages(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1154,7 +1151,7 @@ async def test_list_flows_async_pages(): def test_get_flow(transport: str = "grpc", request_type=flow.GetFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1168,25 +1165,21 @@ def test_get_flow(transport: str = "grpc", request_type=flow.GetFlowRequest): name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.get_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_get_flow_from_dict(): @@ -1197,7 +1190,7 @@ def test_get_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1205,7 +1198,6 @@ def test_get_flow_empty_call(): client.get_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() @@ -1214,7 +1206,7 @@ async def test_get_flow_async( transport: str = "grpc_asyncio", request_type=flow.GetFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1229,25 +1221,22 @@ async def test_get_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.get_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -1256,17 +1245,17 @@ async def test_get_flow_async_from_dict(): def test_get_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.GetFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: call.return_value = flow.Flow() - client.get_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1281,17 +1270,17 @@ def test_get_flow_field_headers(): @pytest.mark.asyncio async def test_get_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.GetFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - await client.get_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1305,13 +1294,12 @@ async def test_get_flow_field_headers_async(): def test_get_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_flow(name="name_value",) @@ -1320,12 +1308,11 @@ def test_get_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1324,7 @@ def test_get_flow_flattened_error(): @pytest.mark.asyncio async def test_get_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: @@ -1353,13 +1340,12 @@ async def test_get_flow_flattened_async(): # 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_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1371,7 +1357,7 @@ async def test_get_flow_flattened_error_async(): def test_update_flow(transport: str = "grpc", request_type=gcdc_flow.UpdateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1385,25 +1371,21 @@ def test_update_flow(transport: str = "grpc", request_type=gcdc_flow.UpdateFlowR name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.update_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_update_flow_from_dict(): @@ -1414,7 +1396,7 @@ def test_update_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1422,7 +1404,6 @@ def test_update_flow_empty_call(): client.update_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() @@ -1431,7 +1412,7 @@ async def test_update_flow_async( transport: str = "grpc_asyncio", request_type=gcdc_flow.UpdateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1446,25 +1427,22 @@ async def test_update_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.update_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -1473,17 +1451,17 @@ async def test_update_flow_async_from_dict(): def test_update_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = gcdc_flow.UpdateFlowRequest() + request.flow.name = "flow.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: call.return_value = gcdc_flow.Flow() - client.update_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1498,17 +1476,17 @@ def test_update_flow_field_headers(): @pytest.mark.asyncio async def test_update_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = gcdc_flow.UpdateFlowRequest() + request.flow.name = "flow.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.update_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1522,32 +1500,29 @@ async def test_update_flow_field_headers_async(): def test_update_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_flow( flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1555,13 +1530,13 @@ def test_update_flow_flattened_error(): client.update_flow( gcdc_flow.UpdateFlowRequest(), flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: @@ -1573,22 +1548,20 @@ async def test_update_flow_flattened_async(): # using the keyword arguments to the method. response = await client.update_flow( flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,13 +1569,13 @@ async def test_update_flow_flattened_error_async(): await client.update_flow( gcdc_flow.UpdateFlowRequest(), flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_train_flow(transport: str = "grpc", request_type=flow.TrainFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1613,13 +1586,11 @@ def test_train_flow(transport: str = "grpc", request_type=flow.TrainFlowRequest) with mock.patch.object(type(client.transport.train_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() # Establish that the response is the type that we expect. @@ -1634,7 +1605,7 @@ def test_train_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1642,7 +1613,6 @@ def test_train_flow_empty_call(): client.train_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() @@ -1651,7 +1621,7 @@ async def test_train_flow_async( transport: str = "grpc_asyncio", request_type=flow.TrainFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1664,13 +1634,11 @@ async def test_train_flow_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() # Establish that the response is the type that we expect. @@ -1683,17 +1651,17 @@ async def test_train_flow_async_from_dict(): def test_train_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.TrainFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1676,12 @@ def test_train_flow_field_headers(): @pytest.mark.asyncio async def test_train_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.TrainFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1689,6 @@ async def test_train_flow_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1734,13 +1702,12 @@ async def test_train_flow_field_headers_async(): def test_train_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.train_flow(name="name_value",) @@ -1749,12 +1716,11 @@ def test_train_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_train_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1766,7 +1732,7 @@ def test_train_flow_flattened_error(): @pytest.mark.asyncio async def test_train_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: @@ -1784,13 +1750,12 @@ async def test_train_flow_flattened_async(): # 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_train_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1802,7 +1767,7 @@ async def test_train_flow_flattened_error_async(): def test_validate_flow(transport: str = "grpc", request_type=flow.ValidateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1813,19 +1778,15 @@ def test_validate_flow(transport: str = "grpc", request_type=flow.ValidateFlowRe with mock.patch.object(type(client.transport.validate_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult(name="name_value",) - response = client.validate_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1837,7 +1798,7 @@ def test_validate_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1845,7 +1806,6 @@ def test_validate_flow_empty_call(): client.validate_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() @@ -1854,7 +1814,7 @@ async def test_validate_flow_async( transport: str = "grpc_asyncio", request_type=flow.ValidateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1867,18 +1827,15 @@ async def test_validate_flow_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult(name="name_value",) ) - response = await client.validate_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1888,17 +1845,17 @@ async def test_validate_flow_async_from_dict(): def test_validate_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.ValidateFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.validate_flow), "__call__") as call: call.return_value = flow.FlowValidationResult() - client.validate_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1913,11 +1870,12 @@ def test_validate_flow_field_headers(): @pytest.mark.asyncio async def test_validate_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.ValidateFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1925,7 +1883,6 @@ async def test_validate_flow_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult() ) - await client.validate_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1942,7 +1899,7 @@ def test_get_flow_validation_result( transport: str = "grpc", request_type=flow.GetFlowValidationResultRequest ): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1955,19 +1912,15 @@ def test_get_flow_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult(name="name_value",) - response = client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1979,7 +1932,7 @@ def test_get_flow_validation_result_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 = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1942,6 @@ def test_get_flow_validation_result_empty_call(): client.get_flow_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() @@ -1998,7 +1950,7 @@ async def test_get_flow_validation_result_async( transport: str = "grpc_asyncio", request_type=flow.GetFlowValidationResultRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,18 +1965,15 @@ async def test_get_flow_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult(name="name_value",) ) - response = await client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -2034,11 +1983,12 @@ async def test_get_flow_validation_result_async_from_dict(): def test_get_flow_validation_result_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.GetFlowValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1996,6 @@ def test_get_flow_validation_result_field_headers(): type(client.transport.get_flow_validation_result), "__call__" ) as call: call.return_value = flow.FlowValidationResult() - client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2061,11 +2010,12 @@ def test_get_flow_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_flow_validation_result_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.GetFlowValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2075,7 +2025,6 @@ async def test_get_flow_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult() ) - await client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2089,7 +2038,7 @@ async def test_get_flow_validation_result_field_headers_async(): def test_get_flow_validation_result_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2097,7 +2046,6 @@ def test_get_flow_validation_result_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_flow_validation_result(name="name_value",) @@ -2106,12 +2054,11 @@ def test_get_flow_validation_result_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_flow_validation_result_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2123,7 +2070,7 @@ def test_get_flow_validation_result_flattened_error(): @pytest.mark.asyncio async def test_get_flow_validation_result_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2143,13 +2090,12 @@ async def test_get_flow_validation_result_flattened_async(): # 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_flow_validation_result_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2159,19 +2105,275 @@ async def test_get_flow_validation_result_flattened_error_async(): ) +def test_import_flow(transport: str = "grpc", request_type=flow.ImportFlowRequest): + client = FlowsClient( + 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.import_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_flow_from_dict(): + test_import_flow(request_type=dict) + + +def test_import_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + 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.import_flow), "__call__") as call: + client.import_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + +@pytest.mark.asyncio +async def test_import_flow_async( + transport: str = "grpc_asyncio", request_type=flow.ImportFlowRequest +): + client = FlowsAsyncClient( + 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.import_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_flow_async_from_dict(): + await test_import_flow_async(request_type=dict) + + +def test_import_flow_field_headers(): + client = FlowsClient(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 = flow.ImportFlowRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_flow), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_flow_field_headers_async(): + client = FlowsAsyncClient(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 = flow.ImportFlowRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_flow), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_export_flow(transport: str = "grpc", request_type=flow.ExportFlowRequest): + client = FlowsClient( + 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.export_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_flow_from_dict(): + test_export_flow(request_type=dict) + + +def test_export_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + 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.export_flow), "__call__") as call: + client.export_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + +@pytest.mark.asyncio +async def test_export_flow_async( + transport: str = "grpc_asyncio", request_type=flow.ExportFlowRequest +): + client = FlowsAsyncClient( + 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.export_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_flow_async_from_dict(): + await test_export_flow_async(request_type=dict) + + +def test_export_flow_field_headers(): + client = FlowsClient(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 = flow.ExportFlowRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_flow), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_flow_field_headers_async(): + client = FlowsAsyncClient(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 = flow.ExportFlowRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_flow), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( @@ -2181,7 +2383,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( @@ -2192,7 +2394,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = FlowsClient(transport=transport) assert client.transport is transport @@ -2201,13 +2403,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.FlowsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2219,23 +2421,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.FlowsGrpcTransport,) def test_flows_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.FlowsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2247,7 +2449,7 @@ def test_flows_base_transport(): ) as Transport: Transport.return_value = None transport = transports.FlowsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2261,6 +2463,8 @@ def test_flows_base_transport(): "train_flow", "validate_flow", "get_flow_validation_result", + "import_flow", + "export_flow", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2272,15 +2476,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2296,19 +2525,36 @@ def test_flows_base_transport_with_credentials_file(): def test_flows_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.flows.transports.FlowsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FlowsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2319,14 +2565,38 @@ def test_flows_auth_adc(): ) -def test_flows_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.FlowsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2336,12 +2606,123 @@ def test_flows_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_flows_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,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport], ) def test_flows_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2383,7 +2764,7 @@ def test_flows_grpc_transport_client_cert_source_for_mtls(transport_class): def test_flows_host_no_port(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2393,7 +2774,7 @@ def test_flows_host_no_port(): def test_flows_host_with_port(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2442,9 +2823,9 @@ def test_flows_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2523,7 +2904,7 @@ def test_flows_transport_channel_mtls_with_adc(transport_class): def test_flows_grpc_lro_client(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2536,7 +2917,7 @@ def test_flows_grpc_lro_client(): def test_flows_grpc_lro_async_client(): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2552,7 +2933,6 @@ def test_flow_path(): location = "clam" agent = "whelk" flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2579,7 +2959,6 @@ def test_flow_validation_result_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2606,7 +2985,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2634,7 +3012,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2657,12 +3034,45 @@ def test_parse_page_path(): assert expected == actual -def test_webhook_path(): +def test_transition_route_group_path(): project = "scallop" location = "abalone" agent = "squid" - webhook = "clam" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( + project=project, + location=location, + agent=agent, + flow=flow, + transition_route_group=transition_route_group, + ) + actual = FlowsClient.transition_route_group_path( + project, location, agent, flow, transition_route_group + ) + assert expected == actual + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = FlowsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_transition_route_group_path(path) + assert expected == actual + + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2672,10 +3082,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "webhook": "nudibranch", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = FlowsClient.webhook_path(**expected) @@ -2685,8 +3095,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" - + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2696,7 +3105,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "nudibranch", } path = FlowsClient.common_billing_account_path(**expected) @@ -2706,8 +3115,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" - + folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = FlowsClient.common_folder_path(folder) assert expected == actual @@ -2715,7 +3123,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "mussel", } path = FlowsClient.common_folder_path(**expected) @@ -2725,8 +3133,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" - + organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = FlowsClient.common_organization_path(organization) assert expected == actual @@ -2734,7 +3141,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nautilus", } path = FlowsClient.common_organization_path(**expected) @@ -2744,8 +3151,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" - + project = "scallop" expected = "projects/{project}".format(project=project,) actual = FlowsClient.common_project_path(project) assert expected == actual @@ -2753,7 +3159,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "abalone", } path = FlowsClient.common_project_path(**expected) @@ -2763,9 +3169,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" - + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2775,8 +3180,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "whelk", + "location": "octopus", } path = FlowsClient.common_location_path(**expected) @@ -2790,13 +3195,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep: client = FlowsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep: transport_class = FlowsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_intents.py b/tests/unit/gapic/dialogflowcx_v3/test_intents.py index 55bd7934..3eb0e707 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_intents.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_intents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.intents import IntentsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -82,7 +111,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +126,7 @@ def test_intents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -140,7 +169,7 @@ def test_intents_client_get_transport_class(): def test_intents_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(IntentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_intents_client_client_options_from_dict(): def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -425,19 +454,15 @@ def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRe call.return_value = intent.ListIntentsResponse( next_page_token="next_page_token_value", ) - response = client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == "next_page_token_value" @@ -449,7 +474,7 @@ def test_list_intents_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -457,7 +482,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -466,7 +490,7 @@ async def test_list_intents_async( transport: str = "grpc_asyncio", request_type=intent.ListIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -479,18 +503,15 @@ async def test_list_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListIntentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -500,17 +521,17 @@ async def test_list_intents_async_from_dict(): def test_list_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: call.return_value = intent.ListIntentsResponse() - client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -525,11 +546,12 @@ def test_list_intents_field_headers(): @pytest.mark.asyncio async def test_list_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -537,7 +559,6 @@ async def test_list_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse() ) - await client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -551,13 +572,12 @@ async def test_list_intents_field_headers_async(): def test_list_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_intents(parent="parent_value",) @@ -566,12 +586,11 @@ def test_list_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -583,7 +602,7 @@ def test_list_intents_flattened_error(): @pytest.mark.asyncio async def test_list_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -601,13 +620,12 @@ async def test_list_intents_flattened_async(): # 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_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -618,7 +636,7 @@ async def test_list_intents_flattened_error_async(): def test_list_intents_pager(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -650,7 +668,7 @@ def test_list_intents_pager(): def test_list_intents_pages(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -674,7 +692,7 @@ def test_list_intents_pages(): @pytest.mark.asyncio async def test_list_intents_async_pager(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,7 +723,7 @@ async def test_list_intents_async_pager(): @pytest.mark.asyncio async def test_list_intents_async_pages(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -733,7 +751,7 @@ async def test_list_intents_async_pages(): def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -750,27 +768,19 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques is_fallback=True, description="description_value", ) - response = client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -782,7 +792,7 @@ def test_get_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -790,7 +800,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -799,7 +808,7 @@ async def test_get_intent_async( transport: str = "grpc_asyncio", request_type=intent.GetIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -818,26 +827,19 @@ async def test_get_intent_async( description="description_value", ) ) - response = await client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -847,17 +849,17 @@ async def test_get_intent_async_from_dict(): def test_get_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = intent.Intent() - client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +874,17 @@ def test_get_intent_field_headers(): @pytest.mark.asyncio async def test_get_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - await client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -896,13 +898,12 @@ async def test_get_intent_field_headers_async(): def test_get_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_intent(name="name_value",) @@ -911,12 +912,11 @@ def test_get_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -928,7 +928,7 @@ def test_get_intent_flattened_error(): @pytest.mark.asyncio async def test_get_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: @@ -944,13 +944,12 @@ async def test_get_intent_flattened_async(): # 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_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -964,7 +963,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcdc_intent.CreateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -981,27 +980,19 @@ def test_create_intent( is_fallback=True, description="description_value", ) - response = client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1013,7 +1004,7 @@ def test_create_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1021,7 +1012,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() @@ -1030,7 +1020,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcdc_intent.CreateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1049,26 +1039,19 @@ async def test_create_intent_async( description="description_value", ) ) - response = await client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1078,17 +1061,17 @@ async def test_create_intent_async_from_dict(): def test_create_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = gcdc_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = gcdc_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1103,17 +1086,17 @@ def test_create_intent_field_headers(): @pytest.mark.asyncio async def test_create_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = gcdc_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1127,13 +1110,12 @@ async def test_create_intent_field_headers_async(): def test_create_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1144,14 +1126,12 @@ def test_create_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcdc_intent.Intent(name="name_value") def test_create_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1165,7 +1145,7 @@ def test_create_intent_flattened_error(): @pytest.mark.asyncio async def test_create_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: @@ -1183,15 +1163,13 @@ async def test_create_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcdc_intent.Intent(name="name_value") @pytest.mark.asyncio async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1207,7 +1185,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcdc_intent.UpdateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1224,27 +1202,19 @@ def test_update_intent( is_fallback=True, description="description_value", ) - response = client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1256,7 +1226,7 @@ def test_update_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1264,7 +1234,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() @@ -1273,7 +1242,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcdc_intent.UpdateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1292,26 +1261,19 @@ async def test_update_intent_async( description="description_value", ) ) - response = await client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1321,17 +1283,17 @@ async def test_update_intent_async_from_dict(): def test_update_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = gcdc_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = gcdc_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1346,17 +1308,17 @@ def test_update_intent_field_headers(): @pytest.mark.asyncio async def test_update_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = gcdc_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1370,32 +1332,29 @@ async def test_update_intent_field_headers_async(): def test_update_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1403,13 +1362,13 @@ def test_update_intent_flattened_error(): client.update_intent( gcdc_intent.UpdateIntentRequest(), intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: @@ -1421,22 +1380,20 @@ async def test_update_intent_flattened_async(): # using the keyword arguments to the method. response = await client.update_intent( intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1444,7 +1401,7 @@ async def test_update_intent_flattened_error_async(): await client.update_intent( gcdc_intent.UpdateIntentRequest(), intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1452,7 +1409,7 @@ def test_delete_intent( transport: str = "grpc", request_type=intent.DeleteIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1463,13 +1420,11 @@ def test_delete_intent( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1484,7 +1439,7 @@ def test_delete_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1492,7 +1447,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1501,7 +1455,7 @@ async def test_delete_intent_async( transport: str = "grpc_asyncio", request_type=intent.DeleteIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1512,13 +1466,11 @@ async def test_delete_intent_async( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1531,17 +1483,17 @@ async def test_delete_intent_async_from_dict(): def test_delete_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = None - client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1556,17 +1508,17 @@ def test_delete_intent_field_headers(): @pytest.mark.asyncio async def test_delete_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1580,13 +1532,12 @@ async def test_delete_intent_field_headers_async(): def test_delete_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_intent(name="name_value",) @@ -1595,12 +1546,11 @@ def test_delete_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1612,7 +1562,7 @@ def test_delete_intent_flattened_error(): @pytest.mark.asyncio async def test_delete_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: @@ -1628,13 +1578,12 @@ async def test_delete_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1647,16 +1596,16 @@ async def test_delete_intent_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -1666,7 +1615,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -1677,7 +1626,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = IntentsClient(transport=transport) assert client.transport is transport @@ -1686,13 +1635,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.IntentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1704,23 +1653,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.IntentsGrpcTransport,) def test_intents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1732,7 +1681,7 @@ def test_intents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1749,15 +1698,40 @@ def test_intents_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1773,19 +1747,36 @@ def test_intents_base_transport_with_credentials_file(): def test_intents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1796,14 +1787,38 @@ def test_intents_auth_adc(): ) -def test_intents_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.IntentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1813,12 +1828,123 @@ def test_intents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_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,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport], ) def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1860,7 +1986,7 @@ def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_intents_host_no_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1870,7 +1996,7 @@ def test_intents_host_no_port(): def test_intents_host_with_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1921,9 +2047,9 @@ def test_intents_transport_channel_mtls_with_client_cert_source(transport_class) mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2005,7 +2131,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -2032,7 +2157,6 @@ def test_intent_path(): location = "nautilus" agent = "scallop" intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2056,7 +2180,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2077,7 +2200,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2096,7 +2218,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2115,7 +2236,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2135,7 +2255,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2162,7 +2281,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.IntentsTransport, "_prep_wrapped_messages" ) as prep: client = IntentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2171,6 +2290,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = IntentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_pages.py b/tests/unit/gapic/dialogflowcx_v3/test_pages.py index eb3f3413..eac60ce1 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_pages.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_pages.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,25 +23,55 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.pages import PagesAsyncClient 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 ( + _API_CORE_VERSION, +) +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 from google.cloud.dialogflowcx_v3.types import response_message from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +114,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [PagesClient, PagesAsyncClient,]) def test_pages_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +129,7 @@ def test_pages_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [PagesClient, PagesAsyncClient,]) def test_pages_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_pages_client_get_transport_class(): def test_pages_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(PagesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -415,7 +444,7 @@ def test_pages_client_client_options_from_dict(): def test_list_pages(transport: str = "grpc", request_type=page.ListPagesRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -428,19 +457,15 @@ def test_list_pages(transport: str = "grpc", request_type=page.ListPagesRequest) call.return_value = page.ListPagesResponse( next_page_token="next_page_token_value", ) - response = client.list_pages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesPager) - assert response.next_page_token == "next_page_token_value" @@ -452,7 +477,7 @@ def test_list_pages_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -460,7 +485,6 @@ def test_list_pages_empty_call(): client.list_pages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() @@ -469,7 +493,7 @@ async def test_list_pages_async( transport: str = "grpc_asyncio", request_type=page.ListPagesRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,18 +506,15 @@ async def test_list_pages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( page.ListPagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_pages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -503,17 +524,17 @@ async def test_list_pages_async_from_dict(): def test_list_pages_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.ListPagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: call.return_value = page.ListPagesResponse() - client.list_pages(request) # Establish that the underlying gRPC stub method was called. @@ -528,11 +549,12 @@ def test_list_pages_field_headers(): @pytest.mark.asyncio async def test_list_pages_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.ListPagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -540,7 +562,6 @@ async def test_list_pages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( page.ListPagesResponse() ) - await client.list_pages(request) # Establish that the underlying gRPC stub method was called. @@ -554,13 +575,12 @@ async def test_list_pages_field_headers_async(): def test_list_pages_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = page.ListPagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_pages(parent="parent_value",) @@ -569,12 +589,11 @@ def test_list_pages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_pages_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -586,7 +605,7 @@ def test_list_pages_flattened_error(): @pytest.mark.asyncio async def test_list_pages_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -604,13 +623,12 @@ async def test_list_pages_flattened_async(): # 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_pages_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -621,7 +639,7 @@ async def test_list_pages_flattened_error_async(): def test_list_pages_pager(): - client = PagesClient(credentials=credentials.AnonymousCredentials,) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -650,7 +668,7 @@ def test_list_pages_pager(): def test_list_pages_pages(): - client = PagesClient(credentials=credentials.AnonymousCredentials,) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -671,7 +689,7 @@ def test_list_pages_pages(): @pytest.mark.asyncio async def test_list_pages_async_pager(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,7 +717,7 @@ async def test_list_pages_async_pager(): @pytest.mark.asyncio async def test_list_pages_async_pages(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -724,7 +742,7 @@ async def test_list_pages_async_pages(): def test_get_page(transport: str = "grpc", request_type=page.GetPageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -739,23 +757,17 @@ def test_get_page(transport: str = "grpc", request_type=page.GetPageRequest): display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.get_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -767,7 +779,7 @@ def test_get_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -775,7 +787,6 @@ def test_get_page_empty_call(): client.get_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() @@ -784,7 +795,7 @@ async def test_get_page_async( transport: str = "grpc_asyncio", request_type=page.GetPageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -801,22 +812,17 @@ async def test_get_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.get_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() # Establish that the response is the type that we expect. assert isinstance(response, page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -826,17 +832,17 @@ async def test_get_page_async_from_dict(): def test_get_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.GetPageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: call.return_value = page.Page() - client.get_page(request) # Establish that the underlying gRPC stub method was called. @@ -851,17 +857,17 @@ def test_get_page_field_headers(): @pytest.mark.asyncio async def test_get_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.GetPageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - await client.get_page(request) # Establish that the underlying gRPC stub method was called. @@ -875,13 +881,12 @@ async def test_get_page_field_headers_async(): def test_get_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_page(name="name_value",) @@ -890,12 +895,11 @@ def test_get_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -907,7 +911,7 @@ def test_get_page_flattened_error(): @pytest.mark.asyncio async def test_get_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: @@ -923,13 +927,12 @@ async def test_get_page_flattened_async(): # 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_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -941,7 +944,7 @@ async def test_get_page_flattened_error_async(): def test_create_page(transport: str = "grpc", request_type=gcdc_page.CreatePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -956,23 +959,17 @@ def test_create_page(transport: str = "grpc", request_type=gcdc_page.CreatePageR display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.create_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -984,7 +981,7 @@ def test_create_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -992,7 +989,6 @@ def test_create_page_empty_call(): client.create_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() @@ -1001,7 +997,7 @@ async def test_create_page_async( transport: str = "grpc_asyncio", request_type=gcdc_page.CreatePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1018,22 +1014,17 @@ async def test_create_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.create_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1043,17 +1034,17 @@ async def test_create_page_async_from_dict(): def test_create_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = gcdc_page.CreatePageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: call.return_value = gcdc_page.Page() - client.create_page(request) # Establish that the underlying gRPC stub method was called. @@ -1068,17 +1059,17 @@ def test_create_page_field_headers(): @pytest.mark.asyncio async def test_create_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = gcdc_page.CreatePageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.create_page(request) # Establish that the underlying gRPC stub method was called. @@ -1092,13 +1083,12 @@ async def test_create_page_field_headers_async(): def test_create_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_page( @@ -1109,14 +1099,12 @@ def test_create_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].page == gcdc_page.Page(name="name_value") def test_create_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1130,7 +1118,7 @@ def test_create_page_flattened_error(): @pytest.mark.asyncio async def test_create_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: @@ -1148,15 +1136,13 @@ async def test_create_page_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].page == gcdc_page.Page(name="name_value") @pytest.mark.asyncio async def test_create_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1170,7 +1156,7 @@ async def test_create_page_flattened_error_async(): def test_update_page(transport: str = "grpc", request_type=gcdc_page.UpdatePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1185,23 +1171,17 @@ def test_update_page(transport: str = "grpc", request_type=gcdc_page.UpdatePageR display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.update_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1213,7 +1193,7 @@ def test_update_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1221,7 +1201,6 @@ def test_update_page_empty_call(): client.update_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() @@ -1230,7 +1209,7 @@ async def test_update_page_async( transport: str = "grpc_asyncio", request_type=gcdc_page.UpdatePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1247,22 +1226,17 @@ async def test_update_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.update_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1272,17 +1246,17 @@ async def test_update_page_async_from_dict(): def test_update_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = gcdc_page.UpdatePageRequest() + request.page.name = "page.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: call.return_value = gcdc_page.Page() - client.update_page(request) # Establish that the underlying gRPC stub method was called. @@ -1297,17 +1271,17 @@ def test_update_page_field_headers(): @pytest.mark.asyncio async def test_update_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = gcdc_page.UpdatePageRequest() + request.page.name = "page.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.update_page(request) # Establish that the underlying gRPC stub method was called. @@ -1321,32 +1295,29 @@ async def test_update_page_field_headers_async(): def test_update_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_page( page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1354,13 +1325,13 @@ def test_update_page_flattened_error(): client.update_page( gcdc_page.UpdatePageRequest(), page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: @@ -1372,22 +1343,20 @@ async def test_update_page_flattened_async(): # using the keyword arguments to the method. response = await client.update_page( page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1395,13 +1364,13 @@ async def test_update_page_flattened_error_async(): await client.update_page( gcdc_page.UpdatePageRequest(), page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_delete_page(transport: str = "grpc", request_type=page.DeletePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1412,13 +1381,11 @@ def test_delete_page(transport: str = "grpc", request_type=page.DeletePageReques with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() # Establish that the response is the type that we expect. @@ -1433,7 +1400,7 @@ def test_delete_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1441,7 +1408,6 @@ def test_delete_page_empty_call(): client.delete_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() @@ -1450,7 +1416,7 @@ async def test_delete_page_async( transport: str = "grpc_asyncio", request_type=page.DeletePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1461,13 +1427,11 @@ async def test_delete_page_async( with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() # Establish that the response is the type that we expect. @@ -1480,17 +1444,17 @@ async def test_delete_page_async_from_dict(): def test_delete_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.DeletePageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: call.return_value = None - client.delete_page(request) # Establish that the underlying gRPC stub method was called. @@ -1505,17 +1469,17 @@ def test_delete_page_field_headers(): @pytest.mark.asyncio async def test_delete_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.DeletePageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_page(request) # Establish that the underlying gRPC stub method was called. @@ -1529,13 +1493,12 @@ async def test_delete_page_field_headers_async(): def test_delete_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_page(name="name_value",) @@ -1544,12 +1507,11 @@ def test_delete_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1561,7 +1523,7 @@ def test_delete_page_flattened_error(): @pytest.mark.asyncio async def test_delete_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: @@ -1577,13 +1539,12 @@ async def test_delete_page_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,16 +1557,16 @@ async def test_delete_page_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( @@ -1615,7 +1576,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( @@ -1626,7 +1587,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PagesClient(transport=transport) assert client.transport is transport @@ -1635,13 +1596,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.PagesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1653,23 +1614,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.PagesGrpcTransport,) def test_pages_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1681,7 +1642,7 @@ def test_pages_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1698,15 +1659,40 @@ def test_pages_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1722,19 +1708,36 @@ def test_pages_base_transport_with_credentials_file(): def test_pages_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.pages.transports.PagesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PagesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1745,14 +1748,38 @@ def test_pages_auth_adc(): ) -def test_pages_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PagesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1762,12 +1789,123 @@ def test_pages_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_pages_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,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport], ) def test_pages_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1809,7 +1947,7 @@ def test_pages_grpc_transport_client_cert_source_for_mtls(transport_class): def test_pages_host_no_port(): client = PagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1819,7 +1957,7 @@ def test_pages_host_no_port(): def test_pages_host_with_port(): client = PagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1868,9 +2006,9 @@ def test_pages_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1952,7 +2090,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -1979,7 +2116,6 @@ def test_flow_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2006,7 +2142,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2034,7 +2169,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2063,7 +2197,6 @@ def test_transition_route_group_path(): agent = "squid" flow = "clam" transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -2097,7 +2230,6 @@ def test_webhook_path(): location = "nautilus" agent = "scallop" webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2121,7 +2253,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2142,7 +2273,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = PagesClient.common_folder_path(folder) assert expected == actual @@ -2161,7 +2291,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = PagesClient.common_organization_path(organization) assert expected == actual @@ -2180,7 +2309,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = PagesClient.common_project_path(project) assert expected == actual @@ -2200,7 +2328,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2225,13 +2352,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep: client = PagesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep: transport_class = PagesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) 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 d0eb88ee..78e89baa 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_security_settings_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.security_settings_service import ( SecuritySettingsServiceAsyncClient, @@ -40,12 +39,42 @@ ) 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 ( + _API_CORE_VERSION, +) +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, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SecuritySettingsServiceClient, SecuritySettingsServiceAsyncClient,] ) def test_security_settings_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -114,7 +143,7 @@ def test_security_settings_service_client_from_service_account_info(client_class "client_class", [SecuritySettingsServiceClient, SecuritySettingsServiceAsyncClient,] ) def test_security_settings_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -171,7 +200,7 @@ def test_security_settings_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecuritySettingsServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -478,7 +507,7 @@ def test_create_security_settings( request_type=gcdc_security_settings.CreateSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -501,35 +530,26 @@ def test_create_security_settings( ], retention_window_days=2271, ) - response = client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -543,7 +563,7 @@ def test_create_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -553,7 +573,6 @@ def test_create_security_settings_empty_call(): client.create_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() @@ -563,7 +582,7 @@ async def test_create_security_settings_async( request_type=gcdc_security_settings.CreateSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -587,34 +606,26 @@ async def test_create_security_settings_async( ], ) ) - response = await client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -627,12 +638,13 @@ async def test_create_security_settings_async_from_dict(): def test_create_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -640,7 +652,6 @@ def test_create_security_settings_field_headers(): type(client.transport.create_security_settings), "__call__" ) as call: call.return_value = gcdc_security_settings.SecuritySettings() - client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -656,12 +667,13 @@ def test_create_security_settings_field_headers(): @pytest.mark.asyncio async def test_create_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -671,7 +683,6 @@ async def test_create_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_security_settings.SecuritySettings() ) - await client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -686,7 +697,7 @@ async def test_create_security_settings_field_headers_async(): def test_create_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -695,7 +706,6 @@ def test_create_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_security_settings( @@ -709,9 +719,7 @@ def test_create_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) @@ -719,7 +727,7 @@ def test_create_security_settings_flattened(): def test_create_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -737,7 +745,7 @@ def test_create_security_settings_flattened_error(): @pytest.mark.asyncio async def test_create_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -763,9 +771,7 @@ async def test_create_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) @@ -774,7 +780,7 @@ async def test_create_security_settings_flattened_async(): @pytest.mark.asyncio async def test_create_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -793,7 +799,7 @@ def test_get_security_settings( transport: str = "grpc", request_type=security_settings.GetSecuritySettingsRequest ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -816,35 +822,26 @@ def test_get_security_settings( ], retention_window_days=2271, ) - response = client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -858,7 +855,7 @@ def test_get_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -868,7 +865,6 @@ def test_get_security_settings_empty_call(): client.get_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() @@ -878,7 +874,7 @@ async def test_get_security_settings_async( request_type=security_settings.GetSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -902,34 +898,26 @@ async def test_get_security_settings_async( ], ) ) - response = await client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -942,12 +930,13 @@ async def test_get_security_settings_async_from_dict(): def test_get_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -955,7 +944,6 @@ def test_get_security_settings_field_headers(): type(client.transport.get_security_settings), "__call__" ) as call: call.return_value = security_settings.SecuritySettings() - client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -971,12 +959,13 @@ def test_get_security_settings_field_headers(): @pytest.mark.asyncio async def test_get_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -986,7 +975,6 @@ async def test_get_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( security_settings.SecuritySettings() ) - await client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1001,7 +989,7 @@ async def test_get_security_settings_field_headers_async(): def test_get_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1010,7 +998,6 @@ def test_get_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_security_settings(name="name_value",) @@ -1019,13 +1006,12 @@ def test_get_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1039,7 +1025,7 @@ def test_get_security_settings_flattened_error(): @pytest.mark.asyncio async def test_get_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1060,14 +1046,13 @@ async def test_get_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1083,7 +1068,7 @@ def test_update_security_settings( request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1106,35 +1091,26 @@ def test_update_security_settings( ], retention_window_days=2271, ) - response = client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -1148,7 +1124,7 @@ def test_update_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1158,7 +1134,6 @@ def test_update_security_settings_empty_call(): client.update_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() @@ -1168,7 +1143,7 @@ async def test_update_security_settings_async( request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1192,34 +1167,26 @@ async def test_update_security_settings_async( ], ) ) - response = await client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -1232,12 +1199,13 @@ async def test_update_security_settings_async_from_dict(): def test_update_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1245,7 +1213,6 @@ def test_update_security_settings_field_headers(): type(client.transport.update_security_settings), "__call__" ) as call: call.return_value = gcdc_security_settings.SecuritySettings() - client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1264,12 +1231,13 @@ def test_update_security_settings_field_headers(): @pytest.mark.asyncio async def test_update_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1279,7 +1247,6 @@ async def test_update_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_security_settings.SecuritySettings() ) - await client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1297,7 +1264,7 @@ async def test_update_security_settings_field_headers_async(): def test_update_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1306,31 +1273,28 @@ def test_update_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_security_settings( security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1341,14 +1305,14 @@ def test_update_security_settings_flattened_error(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1367,25 +1331,23 @@ async def test_update_security_settings_flattened_async(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1396,7 +1358,7 @@ async def test_update_security_settings_flattened_error_async(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1404,7 +1366,7 @@ def test_list_security_settings( transport: str = "grpc", request_type=security_settings.ListSecuritySettingsRequest ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1419,19 +1381,15 @@ def test_list_security_settings( call.return_value = security_settings.ListSecuritySettingsResponse( next_page_token="next_page_token_value", ) - response = client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsPager) - assert response.next_page_token == "next_page_token_value" @@ -1443,7 +1401,7 @@ def test_list_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1453,7 +1411,6 @@ def test_list_security_settings_empty_call(): client.list_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() @@ -1463,7 +1420,7 @@ async def test_list_security_settings_async( request_type=security_settings.ListSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1480,18 +1437,15 @@ async def test_list_security_settings_async( next_page_token="next_page_token_value", ) ) - response = await client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1502,12 +1456,13 @@ async def test_list_security_settings_async_from_dict(): def test_list_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1470,6 @@ def test_list_security_settings_field_headers(): type(client.transport.list_security_settings), "__call__" ) as call: call.return_value = security_settings.ListSecuritySettingsResponse() - client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1531,12 +1485,13 @@ def test_list_security_settings_field_headers(): @pytest.mark.asyncio async def test_list_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1546,7 +1501,6 @@ async def test_list_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( security_settings.ListSecuritySettingsResponse() ) - await client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1561,7 +1515,7 @@ async def test_list_security_settings_field_headers_async(): def test_list_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1570,7 +1524,6 @@ def test_list_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = security_settings.ListSecuritySettingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_security_settings(parent="parent_value",) @@ -1579,13 +1532,12 @@ def test_list_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1599,7 +1551,7 @@ def test_list_security_settings_flattened_error(): @pytest.mark.asyncio async def test_list_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1620,14 +1572,13 @@ async def test_list_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1640,7 +1591,7 @@ async def test_list_security_settings_flattened_error_async(): def test_list_security_settings_pager(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1688,7 +1639,7 @@ def test_list_security_settings_pager(): def test_list_security_settings_pages(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1728,7 +1679,7 @@ def test_list_security_settings_pages(): @pytest.mark.asyncio async def test_list_security_settings_async_pager(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1775,7 +1726,7 @@ async def test_list_security_settings_async_pager(): @pytest.mark.asyncio async def test_list_security_settings_async_pages(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1821,7 +1772,7 @@ def test_delete_security_settings( request_type=security_settings.DeleteSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1834,13 +1785,11 @@ def test_delete_security_settings( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() # Establish that the response is the type that we expect. @@ -1855,7 +1804,7 @@ def test_delete_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1865,7 +1814,6 @@ def test_delete_security_settings_empty_call(): client.delete_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() @@ -1875,7 +1823,7 @@ async def test_delete_security_settings_async( request_type=security_settings.DeleteSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1888,13 +1836,11 @@ async def test_delete_security_settings_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() # Establish that the response is the type that we expect. @@ -1908,12 +1854,13 @@ async def test_delete_security_settings_async_from_dict(): def test_delete_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1921,7 +1868,6 @@ def test_delete_security_settings_field_headers(): type(client.transport.delete_security_settings), "__call__" ) as call: call.return_value = None - client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1937,12 +1883,13 @@ def test_delete_security_settings_field_headers(): @pytest.mark.asyncio async def test_delete_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1950,7 +1897,6 @@ async def test_delete_security_settings_field_headers_async(): type(client.transport.delete_security_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1965,7 +1911,7 @@ async def test_delete_security_settings_field_headers_async(): def test_delete_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1974,7 +1920,6 @@ def test_delete_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_security_settings(name="name_value",) @@ -1983,13 +1928,12 @@ def test_delete_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2003,7 +1947,7 @@ def test_delete_security_settings_flattened_error(): @pytest.mark.asyncio async def test_delete_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2022,14 +1966,13 @@ async def test_delete_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2043,16 +1986,16 @@ async def test_delete_security_settings_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( @@ -2062,7 +2005,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( @@ -2073,7 +2016,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecuritySettingsServiceClient(transport=transport) assert client.transport is transport @@ -2082,13 +2025,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2103,8 +2046,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -2112,7 +2055,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.SecuritySettingsServiceGrpcTransport, @@ -2121,9 +2064,9 @@ def test_transport_grpc_default(): def test_security_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SecuritySettingsServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2135,7 +2078,7 @@ def test_security_settings_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecuritySettingsServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2152,15 +2095,40 @@ def test_security_settings_service_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2176,19 +2144,36 @@ def test_security_settings_service_base_transport_with_credentials_file(): def test_security_settings_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecuritySettingsServiceTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2199,14 +2184,44 @@ def test_security_settings_service_auth_adc(): ) -def test_security_settings_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SecuritySettingsServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2216,6 +2231,123 @@ def test_security_settings_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_security_settings_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "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,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2226,7 +2358,7 @@ def test_security_settings_service_transport_auth_adc(): def test_security_settings_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2268,7 +2400,7 @@ def test_security_settings_service_grpc_transport_client_cert_source_for_mtls( def test_security_settings_service_host_no_port(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2278,7 +2410,7 @@ def test_security_settings_service_host_no_port(): def test_security_settings_service_host_with_port(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2334,9 +2466,9 @@ def test_security_settings_service_transport_channel_mtls_with_client_cert_sourc mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2420,7 +2552,6 @@ def test_security_settings_path(): project = "squid" location = "clam" security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @@ -2445,7 +2576,6 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2466,7 +2596,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SecuritySettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -2485,7 +2614,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SecuritySettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -2504,7 +2632,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SecuritySettingsServiceClient.common_project_path(project) assert expected == actual @@ -2524,7 +2651,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2551,7 +2677,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages" ) as prep: client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2560,6 +2686,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecuritySettingsServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) 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 530e9a89..a1ced677 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_session_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) 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 ( + _API_CORE_VERSION, +) +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 ( session_entity_type as gcdc_session_entity_type, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_session_entity_types_client_from_service_account_info(client_class): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_session_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionEntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -467,7 +496,7 @@ def test_list_session_entity_types( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,19 +511,15 @@ def test_list_session_entity_types( call.return_value = session_entity_type.ListSessionEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -506,7 +531,7 @@ def test_list_session_entity_types_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -516,7 +541,6 @@ def test_list_session_entity_types_empty_call(): client.list_session_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() @@ -526,7 +550,7 @@ async def test_list_session_entity_types_async( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,18 +567,15 @@ async def test_list_session_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -564,11 +585,14 @@ async def test_list_session_entity_types_async_from_dict(): def test_list_session_entity_types_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -576,7 +600,6 @@ def test_list_session_entity_types_field_headers(): type(client.transport.list_session_entity_types), "__call__" ) as call: call.return_value = session_entity_type.ListSessionEntityTypesResponse() - client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -592,12 +615,13 @@ def test_list_session_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_session_entity_types_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -607,7 +631,6 @@ async def test_list_session_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.ListSessionEntityTypesResponse() ) - await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -621,7 +644,9 @@ async def test_list_session_entity_types_field_headers_async(): def test_list_session_entity_types_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -629,7 +654,6 @@ def test_list_session_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.ListSessionEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_session_entity_types(parent="parent_value",) @@ -638,12 +662,13 @@ def test_list_session_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +681,7 @@ def test_list_session_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_session_entity_types_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -677,14 +702,13 @@ async def test_list_session_entity_types_flattened_async(): # 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_session_entity_types_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -696,7 +720,7 @@ async def test_list_session_entity_types_flattened_error_async(): def test_list_session_entity_types_pager(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +768,7 @@ def test_list_session_entity_types_pager(): def test_list_session_entity_types_pages(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -783,7 +807,7 @@ def test_list_session_entity_types_pages(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pager(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +856,7 @@ async def test_list_session_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pages(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -878,7 +902,7 @@ def test_get_session_entity_type( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -894,21 +918,16 @@ def test_get_session_entity_type( name="name_value", entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -923,7 +942,7 @@ def test_get_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -933,7 +952,6 @@ def test_get_session_entity_type_empty_call(): client.get_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() @@ -943,7 +961,7 @@ async def test_get_session_entity_type_async( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -961,20 +979,16 @@ async def test_get_session_entity_type_async( entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -987,11 +1001,14 @@ async def test_get_session_entity_type_async_from_dict(): def test_get_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -999,7 +1016,6 @@ def test_get_session_entity_type_field_headers(): type(client.transport.get_session_entity_type), "__call__" ) as call: call.return_value = session_entity_type.SessionEntityType() - client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1015,12 +1031,13 @@ def test_get_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1030,7 +1047,6 @@ async def test_get_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.SessionEntityType() ) - await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1044,7 +1060,9 @@ async def test_get_session_entity_type_field_headers_async(): def test_get_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1052,7 +1070,6 @@ def test_get_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_session_entity_type(name="name_value",) @@ -1061,12 +1078,13 @@ def test_get_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1079,7 +1097,7 @@ def test_get_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,14 +1118,13 @@ async def test_get_session_entity_type_flattened_async(): # 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_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1123,7 +1140,7 @@ def test_create_session_entity_type( request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1139,21 +1156,16 @@ def test_create_session_entity_type( name="name_value", entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1168,7 +1180,7 @@ def test_create_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1178,7 +1190,6 @@ def test_create_session_entity_type_empty_call(): client.create_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1206,20 +1217,16 @@ async def test_create_session_entity_type_async( entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1232,11 +1239,14 @@ async def test_create_session_entity_type_async_from_dict(): def test_create_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1244,7 +1254,6 @@ def test_create_session_entity_type_field_headers(): type(client.transport.create_session_entity_type), "__call__" ) as call: call.return_value = gcdc_session_entity_type.SessionEntityType() - client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1260,12 +1269,13 @@ def test_create_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1275,7 +1285,6 @@ async def test_create_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_session_entity_type.SessionEntityType() ) - await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1289,7 +1298,9 @@ async def test_create_session_entity_type_field_headers_async(): def test_create_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1297,7 +1308,6 @@ def test_create_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_session_entity_type( @@ -1311,9 +1321,7 @@ def test_create_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( @@ -1322,7 +1330,9 @@ def test_create_session_entity_type_flattened(): def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1349,7 @@ def test_create_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1365,9 +1375,7 @@ async def test_create_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( @@ -1378,7 +1386,7 @@ async def test_create_session_entity_type_flattened_async(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1398,7 +1406,7 @@ def test_update_session_entity_type( request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1414,21 +1422,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1443,7 +1446,7 @@ def test_update_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1453,7 +1456,6 @@ def test_update_session_entity_type_empty_call(): client.update_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1463,7 +1465,7 @@ async def test_update_session_entity_type_async( request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1481,20 +1483,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1507,11 +1505,14 @@ async def test_update_session_entity_type_async_from_dict(): def test_update_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1519,7 +1520,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcdc_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1538,12 +1538,13 @@ def test_update_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1553,7 +1554,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1570,7 +1570,9 @@ async def test_update_session_entity_type_field_headers_async(): def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1578,32 +1580,31 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_session_entity_type( session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1613,14 +1614,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1639,27 +1640,25 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1670,7 +1669,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1679,7 +1678,7 @@ def test_delete_session_entity_type( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1692,13 +1691,11 @@ def test_delete_session_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1713,7 +1710,7 @@ def test_delete_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1723,7 +1720,6 @@ def test_delete_session_entity_type_empty_call(): client.delete_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() @@ -1733,7 +1729,7 @@ async def test_delete_session_entity_type_async( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1746,13 +1742,11 @@ async def test_delete_session_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1765,11 +1759,14 @@ async def test_delete_session_entity_type_async_from_dict(): def test_delete_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1777,7 +1774,6 @@ def test_delete_session_entity_type_field_headers(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = None - client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1793,12 +1789,13 @@ def test_delete_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1806,7 +1803,6 @@ async def test_delete_session_entity_type_field_headers_async(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1820,7 +1816,9 @@ async def test_delete_session_entity_type_field_headers_async(): def test_delete_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1828,7 +1826,6 @@ def test_delete_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_session_entity_type(name="name_value",) @@ -1837,12 +1834,13 @@ def test_delete_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1855,7 +1853,7 @@ def test_delete_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1874,14 +1872,13 @@ async def test_delete_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1895,16 +1892,16 @@ async def test_delete_session_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1914,7 +1911,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1925,7 +1922,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionEntityTypesClient(transport=transport) assert client.transport is transport @@ -1934,13 +1931,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1955,23 +1952,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.SessionEntityTypesGrpcTransport,) def test_session_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1983,7 +1982,7 @@ def test_session_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2000,15 +1999,40 @@ def test_session_entity_types_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2024,19 +2048,36 @@ def test_session_entity_types_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2047,14 +2088,44 @@ def test_session_entity_types_auth_adc(): ) -def test_session_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionEntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2064,6 +2135,121 @@ def test_session_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_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,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2074,7 +2260,7 @@ def test_session_entity_types_transport_auth_adc(): def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2116,7 +2302,7 @@ def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( def test_session_entity_types_host_no_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2126,7 +2312,7 @@ def test_session_entity_types_host_no_port(): def test_session_entity_types_host_with_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2182,9 +2368,9 @@ def test_session_entity_types_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2270,7 +2456,6 @@ def test_session_entity_type_path(): agent = "whelk" session = "octopus" entity_type = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -2301,7 +2486,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2322,7 +2506,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2341,7 +2524,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2360,7 +2542,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2380,7 +2561,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2407,7 +2587,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionEntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2416,6 +2596,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionEntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_sessions.py b/tests/unit/gapic/dialogflowcx_v3/test_sessions.py index 47d2e0a8..d0e152c3 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_sessions.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_sessions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,17 +23,23 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 ( + _API_CORE_VERSION, +) +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 @@ -42,8 +47,32 @@ from google.cloud.dialogflowcx_v3.types import session from google.cloud.dialogflowcx_v3.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import struct_pb2 as struct # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_sessions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -147,7 +176,7 @@ def test_sessions_client_get_transport_class(): def test_sessions_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(SessionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -423,7 +452,7 @@ def test_detect_intent( transport: str = "grpc", request_type=session.DetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -436,21 +465,16 @@ def test_detect_intent( call.return_value = session.DetectIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -462,7 +486,7 @@ def test_detect_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -470,7 +494,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() @@ -479,7 +502,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.DetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -494,20 +517,16 @@ async def test_detect_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -517,17 +536,17 @@ async def test_detect_intent_async_from_dict(): def test_detect_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: call.return_value = session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -542,11 +561,12 @@ def test_detect_intent_field_headers(): @pytest.mark.asyncio async def test_detect_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -554,7 +574,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -571,13 +590,12 @@ def test_streaming_detect_intent( transport: str = "grpc", request_type=session.StreamingDetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + 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() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -586,13 +604,11 @@ def test_streaming_detect_intent( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([session.StreamingDetectIntentResponse()]) - response = client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -609,13 +625,12 @@ async def test_streaming_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.StreamingDetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + 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() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -627,13 +642,11 @@ async def test_streaming_detect_intent_async( call.return_value.read = mock.AsyncMock( side_effect=[session.StreamingDetectIntentResponse()] ) - response = await client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -648,7 +661,7 @@ async def test_streaming_detect_intent_async_from_dict(): def test_match_intent(transport: str = "grpc", request_type=session.MatchIntentRequest): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -659,17 +672,14 @@ def test_match_intent(transport: str = "grpc", request_type=session.MatchIntentR with mock.patch.object(type(client.transport.match_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = session.MatchIntentResponse(text="text_value",) - response = client.match_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) @@ -681,7 +691,7 @@ def test_match_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -689,7 +699,6 @@ def test_match_intent_empty_call(): client.match_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() @@ -698,7 +707,7 @@ async def test_match_intent_async( transport: str = "grpc_asyncio", request_type=session.MatchIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -711,13 +720,11 @@ async def test_match_intent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.MatchIntentResponse() ) - response = await client.match_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() # Establish that the response is the type that we expect. @@ -730,17 +737,17 @@ async def test_match_intent_async_from_dict(): def test_match_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.MatchIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.match_intent), "__call__") as call: call.return_value = session.MatchIntentResponse() - client.match_intent(request) # Establish that the underlying gRPC stub method was called. @@ -755,11 +762,12 @@ def test_match_intent_field_headers(): @pytest.mark.asyncio async def test_match_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.MatchIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -767,7 +775,6 @@ async def test_match_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.MatchIntentResponse() ) - await client.match_intent(request) # Establish that the underlying gRPC stub method was called. @@ -784,7 +791,7 @@ def test_fulfill_intent( transport: str = "grpc", request_type=session.FulfillIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -797,21 +804,16 @@ def test_fulfill_intent( call.return_value = session.FulfillIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -823,7 +825,7 @@ def test_fulfill_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -831,7 +833,6 @@ def test_fulfill_intent_empty_call(): client.fulfill_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() @@ -840,7 +841,7 @@ async def test_fulfill_intent_async( transport: str = "grpc_asyncio", request_type=session.FulfillIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -855,20 +856,16 @@ async def test_fulfill_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -878,17 +875,17 @@ async def test_fulfill_intent_async_from_dict(): def test_fulfill_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.FulfillIntentRequest() + request.match_intent_request.session = "match_intent_request.session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call: call.return_value = session.FulfillIntentResponse() - client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. @@ -906,11 +903,12 @@ def test_fulfill_intent_field_headers(): @pytest.mark.asyncio async def test_fulfill_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.FulfillIntentRequest() + request.match_intent_request.session = "match_intent_request.session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -918,7 +916,6 @@ async def test_fulfill_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.FulfillIntentResponse() ) - await client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. @@ -937,16 +934,16 @@ async def test_fulfill_intent_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -956,7 +953,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -967,7 +964,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionsClient(transport=transport) assert client.transport is transport @@ -976,13 +973,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -994,23 +991,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SessionsGrpcTransport,) def test_sessions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1022,7 +1019,7 @@ def test_sessions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1038,15 +1035,40 @@ def test_sessions_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1062,19 +1084,36 @@ def test_sessions_base_transport_with_credentials_file(): def test_sessions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1085,14 +1124,38 @@ def test_sessions_auth_adc(): ) -def test_sessions_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1102,12 +1165,123 @@ def test_sessions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_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,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport], ) def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1149,7 +1323,7 @@ def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_sessions_host_no_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1159,7 +1333,7 @@ def test_sessions_host_no_port(): def test_sessions_host_with_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1210,9 +1384,9 @@ def test_sessions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1294,7 +1468,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -1321,7 +1494,6 @@ def test_flow_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -1348,7 +1520,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -1376,7 +1547,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -1404,7 +1574,6 @@ def test_session_path(): location = "abalone" agent = "squid" session = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format( project=project, location=location, agent=agent, session=session, ) @@ -1432,7 +1601,6 @@ def test_session_entity_type_path(): agent = "winkle" session = "nautilus" entity_type = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -1467,7 +1635,6 @@ def test_transition_route_group_path(): agent = "cuttlefish" flow = "mussel" transition_route_group = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -1501,7 +1668,6 @@ def test_webhook_path(): location = "octopus" agent = "oyster" webhook = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -1525,7 +1691,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1546,7 +1711,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1565,7 +1729,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1584,7 +1747,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1604,7 +1766,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1631,7 +1792,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionsTransport, "_prep_wrapped_messages" ) as prep: client = SessionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1640,6 +1801,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py b/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py index 8f221cbb..2572625a 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_test_cases.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,27 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.test_cases import TestCasesAsyncClient 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 ( + _API_CORE_VERSION, +) +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 @@ -49,11 +54,35 @@ from google.cloud.dialogflowcx_v3.types import test_case as gcdc_test_case from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TestCasesClient, TestCasesAsyncClient,]) def test_test_cases_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -112,7 +141,7 @@ def test_test_cases_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TestCasesClient, TestCasesAsyncClient,]) def test_test_cases_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -163,7 +192,7 @@ def test_test_cases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TestCasesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -447,7 +476,7 @@ def test_list_test_cases( transport: str = "grpc", request_type=test_case.ListTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -460,19 +489,15 @@ def test_list_test_cases( call.return_value = test_case.ListTestCasesResponse( next_page_token="next_page_token_value", ) - response = client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesPager) - assert response.next_page_token == "next_page_token_value" @@ -484,7 +509,7 @@ def test_list_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -492,7 +517,6 @@ def test_list_test_cases_empty_call(): client.list_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() @@ -501,7 +525,7 @@ async def test_list_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ListTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -514,18 +538,15 @@ async def test_list_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCasesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTestCasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -535,17 +556,17 @@ async def test_list_test_cases_async_from_dict(): def test_list_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ListTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: call.return_value = test_case.ListTestCasesResponse() - client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -560,11 +581,12 @@ def test_list_test_cases_field_headers(): @pytest.mark.asyncio async def test_list_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ListTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -572,7 +594,6 @@ async def test_list_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCasesResponse() ) - await client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -586,13 +607,12 @@ async def test_list_test_cases_field_headers_async(): def test_list_test_cases_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = test_case.ListTestCasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_test_cases(parent="parent_value",) @@ -601,12 +621,11 @@ def test_list_test_cases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_test_cases_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -618,7 +637,7 @@ def test_list_test_cases_flattened_error(): @pytest.mark.asyncio async def test_list_test_cases_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -636,13 +655,12 @@ async def test_list_test_cases_flattened_async(): # 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_test_cases_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -653,7 +671,7 @@ async def test_list_test_cases_flattened_error_async(): def test_list_test_cases_pager(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -691,7 +709,7 @@ def test_list_test_cases_pager(): def test_list_test_cases_pages(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -721,7 +739,7 @@ def test_list_test_cases_pages(): @pytest.mark.asyncio async def test_list_test_cases_async_pager(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -758,7 +776,7 @@ async def test_list_test_cases_async_pager(): @pytest.mark.asyncio async def test_list_test_cases_async_pages(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -794,7 +812,7 @@ def test_batch_delete_test_cases( transport: str = "grpc", request_type=test_case.BatchDeleteTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -807,13 +825,11 @@ def test_batch_delete_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() # Establish that the response is the type that we expect. @@ -828,7 +844,7 @@ def test_batch_delete_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -838,7 +854,6 @@ def test_batch_delete_test_cases_empty_call(): client.batch_delete_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() @@ -847,7 +862,7 @@ async def test_batch_delete_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.BatchDeleteTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -860,13 +875,11 @@ async def test_batch_delete_test_cases_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() # Establish that the response is the type that we expect. @@ -879,11 +892,12 @@ async def test_batch_delete_test_cases_async_from_dict(): def test_batch_delete_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.BatchDeleteTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -891,7 +905,6 @@ def test_batch_delete_test_cases_field_headers(): type(client.transport.batch_delete_test_cases), "__call__" ) as call: call.return_value = None - client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -906,11 +919,12 @@ def test_batch_delete_test_cases_field_headers(): @pytest.mark.asyncio async def test_batch_delete_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.BatchDeleteTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -918,7 +932,6 @@ async def test_batch_delete_test_cases_field_headers_async(): type(client.transport.batch_delete_test_cases), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -932,7 +945,7 @@ async def test_batch_delete_test_cases_field_headers_async(): def test_batch_delete_test_cases_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -940,7 +953,6 @@ def test_batch_delete_test_cases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_test_cases(parent="parent_value",) @@ -949,12 +961,11 @@ def test_batch_delete_test_cases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_batch_delete_test_cases_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -966,7 +977,7 @@ def test_batch_delete_test_cases_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_test_cases_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -984,13 +995,12 @@ async def test_batch_delete_test_cases_flattened_async(): # 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_batch_delete_test_cases_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1004,7 +1014,7 @@ def test_get_test_case( transport: str = "grpc", request_type=test_case.GetTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1020,25 +1030,18 @@ def test_get_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.get_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1050,7 +1053,7 @@ def test_get_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1061,6 @@ def test_get_test_case_empty_call(): client.get_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() @@ -1067,7 +1069,7 @@ async def test_get_test_case_async( transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1085,24 +1087,18 @@ async def test_get_test_case_async( notes="notes_value", ) ) - response = await client.get_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1112,17 +1108,17 @@ async def test_get_test_case_async_from_dict(): def test_get_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.GetTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: call.return_value = test_case.TestCase() - client.get_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1137,17 +1133,17 @@ def test_get_test_case_field_headers(): @pytest.mark.asyncio async def test_get_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.GetTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - await client.get_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1161,13 +1157,12 @@ async def test_get_test_case_field_headers_async(): def test_get_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_test_case(name="name_value",) @@ -1176,12 +1171,11 @@ def test_get_test_case_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1193,7 +1187,7 @@ def test_get_test_case_flattened_error(): @pytest.mark.asyncio async def test_get_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: @@ -1209,13 +1203,12 @@ async def test_get_test_case_flattened_async(): # 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_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1229,7 +1222,7 @@ def test_create_test_case( transport: str = "grpc", request_type=gcdc_test_case.CreateTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1245,25 +1238,18 @@ def test_create_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.create_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1275,7 +1261,7 @@ def test_create_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1269,6 @@ def test_create_test_case_empty_call(): client.create_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() @@ -1292,7 +1277,7 @@ async def test_create_test_case_async( transport: str = "grpc_asyncio", request_type=gcdc_test_case.CreateTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1310,24 +1295,18 @@ async def test_create_test_case_async( notes="notes_value", ) ) - response = await client.create_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1337,17 +1316,17 @@ async def test_create_test_case_async_from_dict(): def test_create_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = gcdc_test_case.CreateTestCaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: call.return_value = gcdc_test_case.TestCase() - client.create_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1362,11 +1341,12 @@ def test_create_test_case_field_headers(): @pytest.mark.asyncio async def test_create_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = gcdc_test_case.CreateTestCaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1374,7 +1354,6 @@ async def test_create_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_test_case.TestCase() ) - await client.create_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1388,13 +1367,12 @@ async def test_create_test_case_field_headers_async(): def test_create_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_test_case( @@ -1405,14 +1383,12 @@ def test_create_test_case_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") def test_create_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1426,7 +1402,7 @@ def test_create_test_case_flattened_error(): @pytest.mark.asyncio async def test_create_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: @@ -1446,15 +1422,13 @@ async def test_create_test_case_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") @pytest.mark.asyncio async def test_create_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1470,7 +1444,7 @@ def test_update_test_case( transport: str = "grpc", request_type=gcdc_test_case.UpdateTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1486,25 +1460,18 @@ def test_update_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.update_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1516,7 +1483,7 @@ def test_update_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1524,7 +1491,6 @@ def test_update_test_case_empty_call(): client.update_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() @@ -1533,7 +1499,7 @@ async def test_update_test_case_async( transport: str = "grpc_asyncio", request_type=gcdc_test_case.UpdateTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1551,24 +1517,18 @@ async def test_update_test_case_async( notes="notes_value", ) ) - response = await client.update_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1578,17 +1538,17 @@ async def test_update_test_case_async_from_dict(): def test_update_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = gcdc_test_case.UpdateTestCaseRequest() + request.test_case.name = "test_case.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: call.return_value = gcdc_test_case.TestCase() - client.update_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1605,11 +1565,12 @@ def test_update_test_case_field_headers(): @pytest.mark.asyncio async def test_update_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = gcdc_test_case.UpdateTestCaseRequest() + request.test_case.name = "test_case.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1617,7 +1578,6 @@ async def test_update_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_test_case.TestCase() ) - await client.update_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1633,32 +1593,29 @@ async def test_update_test_case_field_headers_async(): def test_update_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_test_case( test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1666,13 +1623,13 @@ def test_update_test_case_flattened_error(): client.update_test_case( gcdc_test_case.UpdateTestCaseRequest(), test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: @@ -1686,22 +1643,20 @@ async def test_update_test_case_flattened_async(): # using the keyword arguments to the method. response = await client.update_test_case( test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1709,7 +1664,7 @@ async def test_update_test_case_flattened_error_async(): await client.update_test_case( gcdc_test_case.UpdateTestCaseRequest(), test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1717,7 +1672,7 @@ def test_run_test_case( transport: str = "grpc", request_type=test_case.RunTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1728,13 +1683,11 @@ def test_run_test_case( with mock.patch.object(type(client.transport.run_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.run_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() # Establish that the response is the type that we expect. @@ -1749,7 +1702,7 @@ def test_run_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1757,7 +1710,6 @@ def test_run_test_case_empty_call(): client.run_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() @@ -1766,7 +1718,7 @@ async def test_run_test_case_async( transport: str = "grpc_asyncio", request_type=test_case.RunTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1779,13 +1731,11 @@ async def test_run_test_case_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.run_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() # Establish that the response is the type that we expect. @@ -1798,17 +1748,17 @@ async def test_run_test_case_async_from_dict(): def test_run_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.RunTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_test_case), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.run_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1823,11 +1773,12 @@ def test_run_test_case_field_headers(): @pytest.mark.asyncio async def test_run_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.RunTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1835,7 +1786,6 @@ async def test_run_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.run_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1852,7 +1802,7 @@ def test_batch_run_test_cases( transport: str = "grpc", request_type=test_case.BatchRunTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1865,13 +1815,11 @@ def test_batch_run_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() # Establish that the response is the type that we expect. @@ -1886,7 +1834,7 @@ def test_batch_run_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1896,7 +1844,6 @@ def test_batch_run_test_cases_empty_call(): client.batch_run_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() @@ -1905,7 +1852,7 @@ async def test_batch_run_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.BatchRunTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1920,13 +1867,11 @@ async def test_batch_run_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() # Establish that the response is the type that we expect. @@ -1939,11 +1884,12 @@ async def test_batch_run_test_cases_async_from_dict(): def test_batch_run_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.BatchRunTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1951,7 +1897,6 @@ def test_batch_run_test_cases_field_headers(): type(client.transport.batch_run_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -1966,11 +1911,12 @@ def test_batch_run_test_cases_field_headers(): @pytest.mark.asyncio async def test_batch_run_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.BatchRunTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1980,7 +1926,6 @@ async def test_batch_run_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -1997,7 +1942,7 @@ def test_calculate_coverage( transport: str = "grpc", request_type=test_case.CalculateCoverageRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2015,19 +1960,15 @@ def test_calculate_coverage( intents=[test_case.IntentCoverage.Intent(intent="intent_value")] ), ) - response = client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == "agent_value" @@ -2039,7 +1980,7 @@ def test_calculate_coverage_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2049,7 +1990,6 @@ def test_calculate_coverage_empty_call(): client.calculate_coverage() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() @@ -2058,7 +1998,7 @@ async def test_calculate_coverage_async( transport: str = "grpc_asyncio", request_type=test_case.CalculateCoverageRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2073,18 +2013,15 @@ async def test_calculate_coverage_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.CalculateCoverageResponse(agent="agent_value",) ) - response = await client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() # Establish that the response is the type that we expect. assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == "agent_value" @@ -2094,11 +2031,12 @@ async def test_calculate_coverage_async_from_dict(): def test_calculate_coverage_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.CalculateCoverageRequest() + request.agent = "agent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2106,7 +2044,6 @@ def test_calculate_coverage_field_headers(): type(client.transport.calculate_coverage), "__call__" ) as call: call.return_value = test_case.CalculateCoverageResponse() - client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. @@ -2121,11 +2058,12 @@ def test_calculate_coverage_field_headers(): @pytest.mark.asyncio async def test_calculate_coverage_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.CalculateCoverageRequest() + request.agent = "agent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2135,7 +2073,6 @@ async def test_calculate_coverage_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.CalculateCoverageResponse() ) - await client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. @@ -2152,7 +2089,7 @@ def test_import_test_cases( transport: str = "grpc", request_type=test_case.ImportTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2165,13 +2102,11 @@ def test_import_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2186,7 +2121,7 @@ def test_import_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2196,7 +2131,6 @@ def test_import_test_cases_empty_call(): client.import_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() @@ -2205,7 +2139,7 @@ async def test_import_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ImportTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2220,13 +2154,11 @@ async def test_import_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2239,11 +2171,12 @@ async def test_import_test_cases_async_from_dict(): def test_import_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ImportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2251,7 +2184,6 @@ def test_import_test_cases_field_headers(): type(client.transport.import_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2266,11 +2198,12 @@ def test_import_test_cases_field_headers(): @pytest.mark.asyncio async def test_import_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ImportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2280,7 +2213,6 @@ async def test_import_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2297,7 +2229,7 @@ def test_export_test_cases( transport: str = "grpc", request_type=test_case.ExportTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2310,13 +2242,11 @@ def test_export_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2331,7 +2261,7 @@ def test_export_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2341,7 +2271,6 @@ def test_export_test_cases_empty_call(): client.export_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() @@ -2350,7 +2279,7 @@ async def test_export_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ExportTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2365,13 +2294,11 @@ async def test_export_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2384,11 +2311,12 @@ async def test_export_test_cases_async_from_dict(): def test_export_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ExportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2396,7 +2324,6 @@ def test_export_test_cases_field_headers(): type(client.transport.export_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2411,11 +2338,12 @@ def test_export_test_cases_field_headers(): @pytest.mark.asyncio async def test_export_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ExportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2425,7 +2353,6 @@ async def test_export_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2442,7 +2369,7 @@ def test_list_test_case_results( transport: str = "grpc", request_type=test_case.ListTestCaseResultsRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2457,19 +2384,15 @@ def test_list_test_case_results( call.return_value = test_case.ListTestCaseResultsResponse( next_page_token="next_page_token_value", ) - response = client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsPager) - assert response.next_page_token == "next_page_token_value" @@ -2481,7 +2404,7 @@ def test_list_test_case_results_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2491,7 +2414,6 @@ def test_list_test_case_results_empty_call(): client.list_test_case_results() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() @@ -2500,7 +2422,7 @@ async def test_list_test_case_results_async( transport: str = "grpc_asyncio", request_type=test_case.ListTestCaseResultsRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2517,18 +2439,15 @@ async def test_list_test_case_results_async( next_page_token="next_page_token_value", ) ) - response = await client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2538,11 +2457,12 @@ async def test_list_test_case_results_async_from_dict(): def test_list_test_case_results_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ListTestCaseResultsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2550,7 +2470,6 @@ def test_list_test_case_results_field_headers(): type(client.transport.list_test_case_results), "__call__" ) as call: call.return_value = test_case.ListTestCaseResultsResponse() - client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. @@ -2565,11 +2484,12 @@ def test_list_test_case_results_field_headers(): @pytest.mark.asyncio async def test_list_test_case_results_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ListTestCaseResultsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2579,7 +2499,6 @@ async def test_list_test_case_results_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCaseResultsResponse() ) - await client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. @@ -2593,7 +2512,7 @@ async def test_list_test_case_results_field_headers_async(): def test_list_test_case_results_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2601,7 +2520,6 @@ def test_list_test_case_results_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = test_case.ListTestCaseResultsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_test_case_results(parent="parent_value",) @@ -2610,12 +2528,11 @@ def test_list_test_case_results_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_test_case_results_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2627,7 +2544,7 @@ def test_list_test_case_results_flattened_error(): @pytest.mark.asyncio async def test_list_test_case_results_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2647,13 +2564,12 @@ async def test_list_test_case_results_flattened_async(): # 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_test_case_results_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2664,7 +2580,7 @@ async def test_list_test_case_results_flattened_error_async(): def test_list_test_case_results_pager(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2709,7 +2625,7 @@ def test_list_test_case_results_pager(): def test_list_test_case_results_pages(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2746,7 +2662,7 @@ def test_list_test_case_results_pages(): @pytest.mark.asyncio async def test_list_test_case_results_async_pager(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2790,7 +2706,7 @@ async def test_list_test_case_results_async_pager(): @pytest.mark.asyncio async def test_list_test_case_results_async_pages(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2829,19 +2745,241 @@ async def test_list_test_case_results_async_pages(): assert page_.raw_page.next_page_token == token +def test_get_test_case_result( + transport: str = "grpc", request_type=test_case.GetTestCaseResultRequest +): + client = TestCasesClient( + 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_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult( + name="name_value", + environment="environment_value", + test_result=test_case.TestResult.PASSED, + ) + response = client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == "name_value" + assert response.environment == "environment_value" + assert response.test_result == test_case.TestResult.PASSED + + +def test_get_test_case_result_from_dict(): + test_get_test_case_result(request_type=dict) + + +def test_get_test_case_result_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 = TestCasesClient( + 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_test_case_result), "__call__" + ) as call: + client.get_test_case_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_result_async( + transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseResultRequest +): + client = TestCasesAsyncClient( + 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_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult( + name="name_value", + environment="environment_value", + test_result=test_case.TestResult.PASSED, + ) + ) + response = await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == "name_value" + assert response.environment == "environment_value" + assert response.test_result == test_case.TestResult.PASSED + + +@pytest.mark.asyncio +async def test_get_test_case_result_async_from_dict(): + await test_get_test_case_result_async(request_type=dict) + + +def test_get_test_case_result_field_headers(): + client = TestCasesClient(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 = test_case.GetTestCaseResultRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + call.return_value = test_case.TestCaseResult() + client.get_test_case_result(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_test_case_result_field_headers_async(): + client = TestCasesAsyncClient(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 = test_case.GetTestCaseResultRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult() + ) + await client.get_test_case_result(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_test_case_result_flattened(): + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case_result(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_test_case_result_flattened_error(): + client = TestCasesClient(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_test_case_result( + test_case.GetTestCaseResultRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_async(): + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case_result(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_test_case_result_flattened_error_async(): + client = TestCasesAsyncClient(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_test_case_result( + test_case.GetTestCaseResultRequest(), name="name_value", + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( @@ -2851,7 +2989,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( @@ -2862,7 +3000,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TestCasesClient(transport=transport) assert client.transport is transport @@ -2871,13 +3009,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TestCasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2889,23 +3027,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.TestCasesGrpcTransport,) def test_test_cases_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TestCasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2917,7 +3055,7 @@ def test_test_cases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TestCasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2934,6 +3072,7 @@ def test_test_cases_base_transport(): "import_test_cases", "export_test_cases", "list_test_case_results", + "get_test_case_result", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2945,15 +3084,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2969,19 +3133,36 @@ def test_test_cases_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TestCasesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2992,14 +3173,38 @@ def test_test_cases_auth_adc(): ) -def test_test_cases_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TestCasesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -3009,12 +3214,125 @@ def test_test_cases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_test_cases_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,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport], ) def test_test_cases_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3056,7 +3374,7 @@ def test_test_cases_grpc_transport_client_cert_source_for_mtls(transport_class): def test_test_cases_host_no_port(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3066,7 +3384,7 @@ def test_test_cases_host_no_port(): def test_test_cases_host_with_port(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3117,9 +3435,9 @@ def test_test_cases_transport_channel_mtls_with_client_cert_source(transport_cla mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3198,7 +3516,7 @@ def test_test_cases_transport_channel_mtls_with_adc(transport_class): def test_test_cases_grpc_lro_client(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3211,7 +3529,7 @@ def test_test_cases_grpc_lro_client(): def test_test_cases_grpc_lro_async_client(): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3226,7 +3544,6 @@ def test_agent_path(): project = "squid" location = "clam" agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @@ -3252,7 +3569,6 @@ def test_entity_type_path(): location = "mussel" agent = "winkle" entity_type = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -3279,7 +3595,6 @@ def test_environment_path(): location = "octopus" agent = "oyster" environment = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @@ -3306,7 +3621,6 @@ def test_flow_path(): location = "abalone" agent = "squid" flow = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -3333,7 +3647,6 @@ def test_intent_path(): location = "mussel" agent = "winkle" intent = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -3361,7 +3674,6 @@ def test_page_path(): agent = "oyster" flow = "nudibranch" page = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -3389,7 +3701,6 @@ def test_test_case_path(): location = "clam" agent = "whelk" test_case = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( project=project, location=location, agent=agent, test_case=test_case, ) @@ -3417,7 +3728,6 @@ def test_test_case_result_path(): agent = "scallop" test_case = "abalone" result = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -3452,7 +3762,6 @@ def test_transition_route_group_path(): agent = "winkle" flow = "nautilus" transition_route_group = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -3486,7 +3795,6 @@ def test_webhook_path(): location = "nudibranch" agent = "cuttlefish" webhook = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -3510,7 +3818,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3531,7 +3838,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TestCasesClient.common_folder_path(folder) assert expected == actual @@ -3550,7 +3856,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TestCasesClient.common_organization_path(organization) assert expected == actual @@ -3569,7 +3874,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TestCasesClient.common_project_path(project) assert expected == actual @@ -3589,7 +3893,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3616,7 +3919,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TestCasesTransport, "_prep_wrapped_messages" ) as prep: client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3625,6 +3928,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TestCasesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) 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 a147c3ff..23367381 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_transition_route_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.transition_route_groups import ( TransitionRouteGroupsAsyncClient, @@ -40,6 +39,12 @@ ) 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 ( + _API_CORE_VERSION, +) +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 @@ -48,8 +53,32 @@ transition_route_group as gcdc_transition_route_group, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -101,7 +130,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TransitionRouteGroupsClient, TransitionRouteGroupsAsyncClient,] ) def test_transition_route_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -118,7 +147,7 @@ def test_transition_route_groups_client_from_service_account_info(client_class): "client_class", [TransitionRouteGroupsClient, TransitionRouteGroupsAsyncClient,] ) def test_transition_route_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -175,7 +204,7 @@ def test_transition_route_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TransitionRouteGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -482,7 +511,7 @@ def test_list_transition_route_groups( request_type=transition_route_group.ListTransitionRouteGroupsRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,19 +526,15 @@ def test_list_transition_route_groups( call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( next_page_token="next_page_token_value", ) - response = client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsPager) - assert response.next_page_token == "next_page_token_value" @@ -521,7 +546,7 @@ def test_list_transition_route_groups_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -531,7 +556,6 @@ def test_list_transition_route_groups_empty_call(): client.list_transition_route_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() @@ -541,7 +565,7 @@ async def test_list_transition_route_groups_async( request_type=transition_route_group.ListTransitionRouteGroupsRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -558,18 +582,15 @@ async def test_list_transition_route_groups_async( next_page_token="next_page_token_value", ) ) - response = await client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -580,12 +601,13 @@ async def test_list_transition_route_groups_async_from_dict(): def test_list_transition_route_groups_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.ListTransitionRouteGroupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -593,7 +615,6 @@ def test_list_transition_route_groups_field_headers(): type(client.transport.list_transition_route_groups), "__call__" ) as call: call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. @@ -609,12 +630,13 @@ def test_list_transition_route_groups_field_headers(): @pytest.mark.asyncio async def test_list_transition_route_groups_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.ListTransitionRouteGroupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -624,7 +646,6 @@ async def test_list_transition_route_groups_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transition_route_group.ListTransitionRouteGroupsResponse() ) - await client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. @@ -639,7 +660,7 @@ async def test_list_transition_route_groups_field_headers_async(): def test_list_transition_route_groups_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -648,7 +669,6 @@ def test_list_transition_route_groups_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_transition_route_groups(parent="parent_value",) @@ -657,13 +677,12 @@ def test_list_transition_route_groups_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_transition_route_groups_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -678,7 +697,7 @@ def test_list_transition_route_groups_flattened_error(): @pytest.mark.asyncio async def test_list_transition_route_groups_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -699,14 +718,13 @@ async def test_list_transition_route_groups_flattened_async(): # 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_transition_route_groups_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -719,7 +737,9 @@ async def test_list_transition_route_groups_flattened_error_async(): def test_list_transition_route_groups_pager(): - client = TransitionRouteGroupsClient(credentials=credentials.AnonymousCredentials,) + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -769,7 +789,9 @@ def test_list_transition_route_groups_pager(): def test_list_transition_route_groups_pages(): - client = TransitionRouteGroupsClient(credentials=credentials.AnonymousCredentials,) + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -810,7 +832,7 @@ def test_list_transition_route_groups_pages(): @pytest.mark.asyncio async def test_list_transition_route_groups_async_pager(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -862,7 +884,7 @@ async def test_list_transition_route_groups_async_pager(): @pytest.mark.asyncio async def test_list_transition_route_groups_async_pages(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -912,7 +934,7 @@ def test_get_transition_route_group( request_type=transition_route_group.GetTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -927,21 +949,16 @@ def test_get_transition_route_group( call.return_value = transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -953,7 +970,7 @@ def test_get_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -963,7 +980,6 @@ def test_get_transition_route_group_empty_call(): client.get_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() @@ -973,7 +989,7 @@ async def test_get_transition_route_group_async( request_type=transition_route_group.GetTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -990,20 +1006,16 @@ async def test_get_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() # Establish that the response is the type that we expect. assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1014,12 +1026,13 @@ async def test_get_transition_route_group_async_from_dict(): def test_get_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.GetTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1027,7 +1040,6 @@ def test_get_transition_route_group_field_headers(): type(client.transport.get_transition_route_group), "__call__" ) as call: call.return_value = transition_route_group.TransitionRouteGroup() - client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1043,12 +1055,13 @@ def test_get_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_get_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.GetTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1071,6 @@ async def test_get_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transition_route_group.TransitionRouteGroup() ) - await client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1073,7 +1085,7 @@ async def test_get_transition_route_group_field_headers_async(): def test_get_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1082,7 +1094,6 @@ def test_get_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_transition_route_group(name="name_value",) @@ -1091,13 +1102,12 @@ def test_get_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1111,7 +1121,7 @@ def test_get_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_get_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1132,14 +1142,13 @@ async def test_get_transition_route_group_flattened_async(): # 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_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1155,7 +1164,7 @@ def test_create_transition_route_group( request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1170,23 +1179,18 @@ def test_create_transition_route_group( call.return_value = gcdc_transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1198,7 +1202,7 @@ def test_create_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1208,7 +1212,6 @@ def test_create_transition_route_group_empty_call(): client.create_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) @@ -1220,7 +1223,7 @@ async def test_create_transition_route_group_async( request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1237,22 +1240,18 @@ async def test_create_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1263,12 +1262,13 @@ async def test_create_transition_route_group_async_from_dict(): def test_create_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1276,7 +1276,6 @@ def test_create_transition_route_group_field_headers(): type(client.transport.create_transition_route_group), "__call__" ) as call: call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1292,12 +1291,13 @@ def test_create_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_create_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1307,7 +1307,6 @@ async def test_create_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_transition_route_group.TransitionRouteGroup() ) - await client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1322,7 +1321,7 @@ async def test_create_transition_route_group_field_headers_async(): def test_create_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1331,7 +1330,6 @@ def test_create_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_transition_route_group( @@ -1345,9 +1343,7 @@ def test_create_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( @@ -1357,7 +1353,7 @@ def test_create_transition_route_group_flattened(): def test_create_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1375,7 +1371,7 @@ def test_create_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_create_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1401,9 +1397,7 @@ async def test_create_transition_route_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( @@ -1414,7 +1408,7 @@ async def test_create_transition_route_group_flattened_async(): @pytest.mark.asyncio async def test_create_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1434,7 +1428,7 @@ def test_update_transition_route_group( request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1449,23 +1443,18 @@ def test_update_transition_route_group( call.return_value = gcdc_transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1477,7 +1466,7 @@ def test_update_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1487,7 +1476,6 @@ def test_update_transition_route_group_empty_call(): client.update_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) @@ -1499,7 +1487,7 @@ async def test_update_transition_route_group_async( request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1516,22 +1504,18 @@ async def test_update_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1542,12 +1526,13 @@ async def test_update_transition_route_group_async_from_dict(): def test_update_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + request.transition_route_group.name = "transition_route_group.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1555,7 +1540,6 @@ def test_update_transition_route_group_field_headers(): type(client.transport.update_transition_route_group), "__call__" ) as call: call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1574,12 +1558,13 @@ def test_update_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_update_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + request.transition_route_group.name = "transition_route_group.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1574,6 @@ async def test_update_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_transition_route_group.TransitionRouteGroup() ) - await client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1607,7 +1591,7 @@ async def test_update_transition_route_group_field_headers_async(): def test_update_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1616,33 +1600,30 @@ def test_update_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_transition_route_group( transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1653,14 +1634,14 @@ def test_update_transition_route_group_flattened_error(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1679,27 +1660,25 @@ async def test_update_transition_route_group_flattened_async(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1710,7 +1689,7 @@ async def test_update_transition_route_group_flattened_error_async(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1719,7 +1698,7 @@ def test_delete_transition_route_group( request_type=transition_route_group.DeleteTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1732,13 +1711,11 @@ def test_delete_transition_route_group( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() # Establish that the response is the type that we expect. @@ -1753,7 +1730,7 @@ def test_delete_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1763,7 +1740,6 @@ def test_delete_transition_route_group_empty_call(): client.delete_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() @@ -1773,7 +1749,7 @@ async def test_delete_transition_route_group_async( request_type=transition_route_group.DeleteTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1786,13 +1762,11 @@ async def test_delete_transition_route_group_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() # Establish that the response is the type that we expect. @@ -1806,12 +1780,13 @@ async def test_delete_transition_route_group_async_from_dict(): def test_delete_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.DeleteTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1819,7 +1794,6 @@ def test_delete_transition_route_group_field_headers(): type(client.transport.delete_transition_route_group), "__call__" ) as call: call.return_value = None - client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1835,12 +1809,13 @@ def test_delete_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_delete_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.DeleteTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1848,7 +1823,6 @@ async def test_delete_transition_route_group_field_headers_async(): type(client.transport.delete_transition_route_group), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1863,7 +1837,7 @@ async def test_delete_transition_route_group_field_headers_async(): def test_delete_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1872,7 +1846,6 @@ def test_delete_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_transition_route_group(name="name_value",) @@ -1881,13 +1854,12 @@ def test_delete_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1902,7 +1874,7 @@ def test_delete_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_delete_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1921,14 +1893,13 @@ async def test_delete_transition_route_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1943,16 +1914,16 @@ async def test_delete_transition_route_group_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( @@ -1962,7 +1933,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( @@ -1973,7 +1944,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TransitionRouteGroupsClient(transport=transport) assert client.transport is transport @@ -1982,13 +1953,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2003,8 +1974,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -2012,16 +1983,16 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance(client.transport, transports.TransitionRouteGroupsGrpcTransport,) def test_transition_route_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TransitionRouteGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2033,7 +2004,7 @@ def test_transition_route_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TransitionRouteGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2050,15 +2021,40 @@ def test_transition_route_groups_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2074,19 +2070,36 @@ def test_transition_route_groups_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TransitionRouteGroupsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2097,14 +2110,44 @@ def test_transition_route_groups_auth_adc(): ) -def test_transition_route_groups_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TransitionRouteGroupsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2114,6 +2157,123 @@ def test_transition_route_groups_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_transition_route_groups_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,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2124,7 +2284,7 @@ def test_transition_route_groups_transport_auth_adc(): def test_transition_route_groups_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2166,7 +2326,7 @@ def test_transition_route_groups_grpc_transport_client_cert_source_for_mtls( def test_transition_route_groups_host_no_port(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2176,7 +2336,7 @@ def test_transition_route_groups_host_no_port(): def test_transition_route_groups_host_with_port(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2232,9 +2392,9 @@ def test_transition_route_groups_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2319,7 +2479,6 @@ def test_flow_path(): location = "clam" agent = "whelk" flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2346,7 +2505,6 @@ def test_intent_path(): location = "nautilus" agent = "scallop" intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2374,7 +2532,6 @@ def test_page_path(): agent = "cuttlefish" flow = "mussel" page = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2403,7 +2560,6 @@ def test_transition_route_group_path(): agent = "oyster" flow = "nudibranch" transition_route_group = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -2437,7 +2593,6 @@ def test_webhook_path(): location = "clam" agent = "whelk" webhook = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2461,7 +2616,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2482,7 +2636,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = TransitionRouteGroupsClient.common_folder_path(folder) assert expected == actual @@ -2501,7 +2654,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = TransitionRouteGroupsClient.common_organization_path(organization) assert expected == actual @@ -2520,7 +2672,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = TransitionRouteGroupsClient.common_project_path(project) assert expected == actual @@ -2540,7 +2691,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2567,7 +2717,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages" ) as prep: client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2576,6 +2726,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TransitionRouteGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_versions.py b/tests/unit/gapic/dialogflowcx_v3/test_versions.py index f0f02f05..86ffdef4 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_versions.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_versions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.versions import VersionsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_versions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_versions_client_get_transport_class(): def test_versions_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(VersionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -426,7 +455,7 @@ def test_list_versions( transport: str = "grpc", request_type=version.ListVersionsRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -439,19 +468,15 @@ def test_list_versions( call.return_value = version.ListVersionsResponse( next_page_token="next_page_token_value", ) - response = client.list_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.ListVersionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == "next_page_token_value" @@ -463,7 +488,7 @@ def test_list_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -471,7 +496,6 @@ def test_list_versions_empty_call(): client.list_versions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.ListVersionsRequest() @@ -480,7 +504,7 @@ async def test_list_versions_async( transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -493,18 +517,15 @@ async def test_list_versions_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( version.ListVersionsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_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.ListVersionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -514,17 +535,17 @@ async def test_list_versions_async_from_dict(): def test_list_versions_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_versions), "__call__") as call: call.return_value = version.ListVersionsResponse() - client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -539,11 +560,12 @@ def test_list_versions_field_headers(): @pytest.mark.asyncio async def test_list_versions_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -551,7 +573,6 @@ async def test_list_versions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( version.ListVersionsResponse() ) - await client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -565,13 +586,12 @@ async def test_list_versions_field_headers_async(): def test_list_versions_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.list_versions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = version.ListVersionsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_versions(parent="parent_value",) @@ -580,12 +600,11 @@ def test_list_versions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_versions_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -597,7 +616,7 @@ def test_list_versions_flattened_error(): @pytest.mark.asyncio async def test_list_versions_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.list_versions), "__call__") as call: @@ -615,13 +634,12 @@ async def test_list_versions_flattened_async(): # 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_versions_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -632,7 +650,7 @@ async def test_list_versions_flattened_error_async(): def test_list_versions_pager(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + 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.list_versions), "__call__") as call: @@ -666,7 +684,7 @@ def test_list_versions_pager(): def test_list_versions_pages(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + 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.list_versions), "__call__") as call: @@ -692,7 +710,7 @@ def test_list_versions_pages(): @pytest.mark.asyncio async def test_list_versions_async_pager(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -725,7 +743,7 @@ async def test_list_versions_async_pager(): @pytest.mark.asyncio async def test_list_versions_async_pages(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -755,7 +773,7 @@ async def test_list_versions_async_pages(): def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -771,25 +789,18 @@ def test_get_version(transport: str = "grpc", request_type=version.GetVersionReq description="description_value", state=version.Version.State.RUNNING, ) - response = client.get_version(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.GetVersionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == version.Version.State.RUNNING @@ -801,7 +812,7 @@ def test_get_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -809,7 +820,6 @@ def test_get_version_empty_call(): client.get_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() @@ -818,7 +828,7 @@ async def test_get_version_async( transport: str = "grpc_asyncio", request_type=version.GetVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -836,24 +846,18 @@ async def test_get_version_async( state=version.Version.State.RUNNING, ) ) - response = await client.get_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == version.Version.State.RUNNING @@ -863,17 +867,17 @@ async def test_get_version_async_from_dict(): def test_get_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = version.Version() - client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -888,17 +892,17 @@ def test_get_version_field_headers(): @pytest.mark.asyncio async def test_get_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) - await client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -912,13 +916,12 @@ async def test_get_version_field_headers_async(): def test_get_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.get_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = version.Version() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_version(name="name_value",) @@ -927,12 +930,11 @@ def test_get_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -944,7 +946,7 @@ def test_get_version_flattened_error(): @pytest.mark.asyncio async def test_get_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.get_version), "__call__") as call: @@ -960,13 +962,12 @@ async def test_get_version_flattened_async(): # 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_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -980,7 +981,7 @@ def test_create_version( transport: str = "grpc", request_type=gcdc_version.CreateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -991,13 +992,11 @@ def test_create_version( with mock.patch.object(type(client.transport.create_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -1012,7 +1011,7 @@ def test_create_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1020,7 +1019,6 @@ def test_create_version_empty_call(): client.create_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() @@ -1029,7 +1027,7 @@ async def test_create_version_async( transport: str = "grpc_asyncio", request_type=gcdc_version.CreateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1042,13 +1040,11 @@ async def test_create_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -1061,17 +1057,17 @@ async def test_create_version_async_from_dict(): def test_create_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1086,11 +1082,12 @@ def test_create_version_field_headers(): @pytest.mark.asyncio async def test_create_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1098,7 +1095,6 @@ async def test_create_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1112,13 +1108,12 @@ async def test_create_version_field_headers_async(): def test_create_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.create_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_version( @@ -1129,14 +1124,12 @@ def test_create_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].version == gcdc_version.Version(name="name_value") def test_create_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1150,7 +1143,7 @@ def test_create_version_flattened_error(): @pytest.mark.asyncio async def test_create_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.create_version), "__call__") as call: @@ -1170,15 +1163,13 @@ async def test_create_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].version == gcdc_version.Version(name="name_value") @pytest.mark.asyncio async def test_create_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1194,7 +1185,7 @@ def test_update_version( transport: str = "grpc", request_type=gcdc_version.UpdateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1210,25 +1201,18 @@ def test_update_version( description="description_value", state=gcdc_version.Version.State.RUNNING, ) - response = client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_version.Version.State.RUNNING @@ -1240,7 +1224,7 @@ def test_update_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1248,7 +1232,6 @@ def test_update_version_empty_call(): client.update_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() @@ -1257,7 +1240,7 @@ async def test_update_version_async( transport: str = "grpc_asyncio", request_type=gcdc_version.UpdateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1275,24 +1258,18 @@ async def test_update_version_async( state=gcdc_version.Version.State.RUNNING, ) ) - response = await client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_version.Version.State.RUNNING @@ -1302,17 +1279,17 @@ async def test_update_version_async_from_dict(): def test_update_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.UpdateVersionRequest() + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_version), "__call__") as call: call.return_value = gcdc_version.Version() - client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1329,11 +1306,12 @@ def test_update_version_field_headers(): @pytest.mark.asyncio async def test_update_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.UpdateVersionRequest() + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1341,7 +1319,6 @@ async def test_update_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_version.Version() ) - await client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1357,32 +1334,29 @@ async def test_update_version_field_headers_async(): def test_update_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.update_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_version.Version() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_version( version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,13 +1364,13 @@ def test_update_version_flattened_error(): client.update_version( gcdc_version.UpdateVersionRequest(), version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.update_version), "__call__") as call: @@ -1410,22 +1384,20 @@ async def test_update_version_flattened_async(): # using the keyword arguments to the method. response = await client.update_version( version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1405,7 @@ async def test_update_version_flattened_error_async(): await client.update_version( gcdc_version.UpdateVersionRequest(), version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1441,7 +1413,7 @@ def test_delete_version( transport: str = "grpc", request_type=version.DeleteVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1452,13 +1424,11 @@ def test_delete_version( with mock.patch.object(type(client.transport.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_version(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.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1473,7 +1443,7 @@ def test_delete_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1481,7 +1451,6 @@ def test_delete_version_empty_call(): client.delete_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.DeleteVersionRequest() @@ -1490,7 +1459,7 @@ async def test_delete_version_async( transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1501,13 +1470,11 @@ async def test_delete_version_async( with mock.patch.object(type(client.transport.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1520,17 +1487,17 @@ async def test_delete_version_async_from_dict(): def test_delete_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = None - client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1545,17 +1512,17 @@ def test_delete_version_field_headers(): @pytest.mark.asyncio async def test_delete_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1569,13 +1536,12 @@ async def test_delete_version_field_headers_async(): def test_delete_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_version(name="name_value",) @@ -1584,12 +1550,11 @@ def test_delete_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1601,7 +1566,7 @@ def test_delete_version_flattened_error(): @pytest.mark.asyncio async def test_delete_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.delete_version), "__call__") as call: @@ -1617,13 +1582,12 @@ async def test_delete_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1635,7 +1599,7 @@ async def test_delete_version_flattened_error_async(): def test_load_version(transport: str = "grpc", request_type=version.LoadVersionRequest): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1646,13 +1610,11 @@ def test_load_version(transport: str = "grpc", request_type=version.LoadVersionR with mock.patch.object(type(client.transport.load_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.load_version(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.LoadVersionRequest() # Establish that the response is the type that we expect. @@ -1667,7 +1629,7 @@ def test_load_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1675,7 +1637,6 @@ def test_load_version_empty_call(): client.load_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() @@ -1684,7 +1645,7 @@ async def test_load_version_async( transport: str = "grpc_asyncio", request_type=version.LoadVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1697,13 +1658,11 @@ async def test_load_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.load_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() # Establish that the response is the type that we expect. @@ -1716,17 +1675,17 @@ async def test_load_version_async_from_dict(): def test_load_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.LoadVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.load_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.load_version(request) # Establish that the underlying gRPC stub method was called. @@ -1741,11 +1700,12 @@ def test_load_version_field_headers(): @pytest.mark.asyncio async def test_load_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.LoadVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1753,7 +1713,6 @@ async def test_load_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.load_version(request) # Establish that the underlying gRPC stub method was called. @@ -1767,13 +1726,12 @@ async def test_load_version_field_headers_async(): def test_load_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.load_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.load_version(name="name_value",) @@ -1782,12 +1740,11 @@ def test_load_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_load_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1799,7 +1756,7 @@ def test_load_version_flattened_error(): @pytest.mark.asyncio async def test_load_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.load_version), "__call__") as call: @@ -1817,13 +1774,12 @@ async def test_load_version_flattened_async(): # 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_load_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1836,16 +1792,16 @@ async def test_load_version_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1855,7 +1811,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1866,7 +1822,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = VersionsClient(transport=transport) assert client.transport is transport @@ -1875,13 +1831,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.VersionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1893,23 +1849,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.VersionsGrpcTransport,) def test_versions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1921,7 +1877,7 @@ def test_versions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1944,15 +1900,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1968,19 +1949,36 @@ def test_versions_base_transport_with_credentials_file(): def test_versions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.versions.transports.VersionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VersionsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1991,14 +1989,38 @@ def test_versions_auth_adc(): ) -def test_versions_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.VersionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2008,12 +2030,123 @@ def test_versions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_versions_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,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], ) def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2055,7 +2188,7 @@ def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_versions_host_no_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2065,7 +2198,7 @@ def test_versions_host_no_port(): def test_versions_host_with_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2116,9 +2249,9 @@ def test_versions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2197,7 +2330,7 @@ def test_versions_transport_channel_mtls_with_adc(transport_class): def test_versions_grpc_lro_client(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2210,7 +2343,7 @@ def test_versions_grpc_lro_client(): def test_versions_grpc_lro_async_client(): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2227,7 +2360,6 @@ def test_version_path(): agent = "whelk" flow = "octopus" version = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2252,7 +2384,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2273,7 +2404,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = VersionsClient.common_folder_path(folder) assert expected == actual @@ -2292,7 +2422,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = VersionsClient.common_organization_path(organization) assert expected == actual @@ -2311,7 +2440,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = VersionsClient.common_project_path(project) assert expected == actual @@ -2331,7 +2459,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2358,7 +2485,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.VersionsTransport, "_prep_wrapped_messages" ) as prep: client = VersionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2367,6 +2494,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = VersionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py b/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py index fcae841e..5ade2328 100644 --- a/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py +++ b/tests/unit/gapic/dialogflowcx_v3/test_webhooks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3.services.webhooks import WebhooksAsyncClient 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [WebhooksClient, WebhooksAsyncClient,]) def test_webhooks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_webhooks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [WebhooksClient, WebhooksAsyncClient,]) def test_webhooks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_webhooks_client_get_transport_class(): def test_webhooks_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(WebhooksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -420,7 +449,7 @@ def test_list_webhooks( transport: str = "grpc", request_type=webhook.ListWebhooksRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -433,19 +462,15 @@ def test_list_webhooks( call.return_value = webhook.ListWebhooksResponse( next_page_token="next_page_token_value", ) - response = client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_webhooks_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -465,7 +490,6 @@ def test_list_webhooks_empty_call(): client.list_webhooks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() @@ -474,7 +498,7 @@ async def test_list_webhooks_async( transport: str = "grpc_asyncio", request_type=webhook.ListWebhooksRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -487,18 +511,15 @@ async def test_list_webhooks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( webhook.ListWebhooksResponse(next_page_token="next_page_token_value",) ) - response = await client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListWebhooksAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_webhooks_async_from_dict(): def test_list_webhooks_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.ListWebhooksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: call.return_value = webhook.ListWebhooksResponse() - client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_webhooks_field_headers(): @pytest.mark.asyncio async def test_list_webhooks_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.ListWebhooksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_webhooks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( webhook.ListWebhooksResponse() ) - await client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_webhooks_field_headers_async(): def test_list_webhooks_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = webhook.ListWebhooksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_webhooks(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_webhooks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_webhooks_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -591,7 +610,7 @@ def test_list_webhooks_flattened_error(): @pytest.mark.asyncio async def test_list_webhooks_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_webhooks_flattened_async(): # 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_webhooks_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -626,7 +644,7 @@ async def test_list_webhooks_flattened_error_async(): def test_list_webhooks_pager(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_webhooks_pager(): def test_list_webhooks_pages(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_webhooks_pages(): @pytest.mark.asyncio async def test_list_webhooks_async_pager(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +737,7 @@ async def test_list_webhooks_async_pager(): @pytest.mark.asyncio async def test_list_webhooks_async_pages(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -749,7 +767,7 @@ async def test_list_webhooks_async_pages(): def test_get_webhook(transport: str = "grpc", request_type=webhook.GetWebhookRequest): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -765,23 +783,17 @@ def test_get_webhook(transport: str = "grpc", request_type=webhook.GetWebhookReq disabled=True, generic_web_service=webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.get_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -793,7 +805,7 @@ def test_get_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -801,7 +813,6 @@ def test_get_webhook_empty_call(): client.get_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() @@ -810,7 +821,7 @@ async def test_get_webhook_async( transport: str = "grpc_asyncio", request_type=webhook.GetWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -825,22 +836,17 @@ async def test_get_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.get_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -850,17 +856,17 @@ async def test_get_webhook_async_from_dict(): def test_get_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.GetWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: call.return_value = webhook.Webhook() - client.get_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -875,17 +881,17 @@ def test_get_webhook_field_headers(): @pytest.mark.asyncio async def test_get_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.GetWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - await client.get_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -899,13 +905,12 @@ async def test_get_webhook_field_headers_async(): def test_get_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_webhook(name="name_value",) @@ -914,12 +919,11 @@ def test_get_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -931,7 +935,7 @@ def test_get_webhook_flattened_error(): @pytest.mark.asyncio async def test_get_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: @@ -947,13 +951,12 @@ async def test_get_webhook_flattened_async(): # 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -967,7 +970,7 @@ def test_create_webhook( transport: str = "grpc", request_type=gcdc_webhook.CreateWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -983,23 +986,17 @@ def test_create_webhook( disabled=True, generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.create_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1011,7 +1008,7 @@ def test_create_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1019,7 +1016,6 @@ def test_create_webhook_empty_call(): client.create_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() @@ -1028,7 +1024,7 @@ async def test_create_webhook_async( transport: str = "grpc_asyncio", request_type=gcdc_webhook.CreateWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1043,22 +1039,17 @@ async def test_create_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.create_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1068,17 +1059,17 @@ async def test_create_webhook_async_from_dict(): def test_create_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = gcdc_webhook.CreateWebhookRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: call.return_value = gcdc_webhook.Webhook() - client.create_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1093,11 +1084,12 @@ def test_create_webhook_field_headers(): @pytest.mark.asyncio async def test_create_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = gcdc_webhook.CreateWebhookRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1105,7 +1097,6 @@ async def test_create_webhook_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_webhook.Webhook() ) - await client.create_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1119,13 +1110,12 @@ async def test_create_webhook_field_headers_async(): def test_create_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_webhook( @@ -1136,14 +1126,12 @@ def test_create_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") def test_create_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1157,7 +1145,7 @@ def test_create_webhook_flattened_error(): @pytest.mark.asyncio async def test_create_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: @@ -1177,15 +1165,13 @@ async def test_create_webhook_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") @pytest.mark.asyncio async def test_create_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1201,7 +1187,7 @@ def test_update_webhook( transport: str = "grpc", request_type=gcdc_webhook.UpdateWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1217,23 +1203,17 @@ def test_update_webhook( disabled=True, generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.update_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1245,7 +1225,7 @@ def test_update_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1253,7 +1233,6 @@ def test_update_webhook_empty_call(): client.update_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() @@ -1262,7 +1241,7 @@ async def test_update_webhook_async( transport: str = "grpc_asyncio", request_type=gcdc_webhook.UpdateWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1277,22 +1256,17 @@ async def test_update_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.update_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1302,17 +1276,17 @@ async def test_update_webhook_async_from_dict(): def test_update_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = gcdc_webhook.UpdateWebhookRequest() + request.webhook.name = "webhook.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: call.return_value = gcdc_webhook.Webhook() - client.update_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1329,11 +1303,12 @@ def test_update_webhook_field_headers(): @pytest.mark.asyncio async def test_update_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = gcdc_webhook.UpdateWebhookRequest() + request.webhook.name = "webhook.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1341,7 +1316,6 @@ async def test_update_webhook_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_webhook.Webhook() ) - await client.update_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1357,32 +1331,29 @@ async def test_update_webhook_field_headers_async(): def test_update_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_webhook( webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,13 +1361,13 @@ def test_update_webhook_flattened_error(): client.update_webhook( gcdc_webhook.UpdateWebhookRequest(), webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: @@ -1410,22 +1381,20 @@ async def test_update_webhook_flattened_async(): # using the keyword arguments to the method. response = await client.update_webhook( webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1402,7 @@ async def test_update_webhook_flattened_error_async(): await client.update_webhook( gcdc_webhook.UpdateWebhookRequest(), webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1441,7 +1410,7 @@ def test_delete_webhook( transport: str = "grpc", request_type=webhook.DeleteWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1452,13 +1421,11 @@ def test_delete_webhook( with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() # Establish that the response is the type that we expect. @@ -1473,7 +1440,7 @@ def test_delete_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1481,7 +1448,6 @@ def test_delete_webhook_empty_call(): client.delete_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() @@ -1490,7 +1456,7 @@ async def test_delete_webhook_async( transport: str = "grpc_asyncio", request_type=webhook.DeleteWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1501,13 +1467,11 @@ async def test_delete_webhook_async( with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() # Establish that the response is the type that we expect. @@ -1520,17 +1484,17 @@ async def test_delete_webhook_async_from_dict(): def test_delete_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.DeleteWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: call.return_value = None - client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1545,17 +1509,17 @@ def test_delete_webhook_field_headers(): @pytest.mark.asyncio async def test_delete_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.DeleteWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1569,13 +1533,12 @@ async def test_delete_webhook_field_headers_async(): def test_delete_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_webhook(name="name_value",) @@ -1584,12 +1547,11 @@ def test_delete_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1601,7 +1563,7 @@ def test_delete_webhook_flattened_error(): @pytest.mark.asyncio async def test_delete_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: @@ -1617,13 +1579,12 @@ async def test_delete_webhook_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1636,16 +1597,16 @@ async def test_delete_webhook_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( @@ -1655,7 +1616,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( @@ -1666,7 +1627,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = WebhooksClient(transport=transport) assert client.transport is transport @@ -1675,13 +1636,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.WebhooksGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1693,23 +1654,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.WebhooksGrpcTransport,) def test_webhooks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.WebhooksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1721,7 +1682,7 @@ def test_webhooks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.WebhooksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1738,15 +1699,40 @@ def test_webhooks_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1762,19 +1748,36 @@ def test_webhooks_base_transport_with_credentials_file(): def test_webhooks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.WebhooksTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1785,14 +1788,38 @@ def test_webhooks_auth_adc(): ) -def test_webhooks_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.WebhooksGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1802,12 +1829,123 @@ def test_webhooks_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_webhooks_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,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport], ) def test_webhooks_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1849,7 +1987,7 @@ def test_webhooks_grpc_transport_client_cert_source_for_mtls(transport_class): def test_webhooks_host_no_port(): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1859,7 +1997,7 @@ def test_webhooks_host_no_port(): def test_webhooks_host_with_port(): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1910,9 +2048,9 @@ def test_webhooks_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1989,12 +2127,37 @@ def test_webhooks_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_webhook_path(): +def test_service_path(): project = "squid" location = "clam" - agent = "whelk" - webhook = "octopus" + namespace = "whelk" + service = "octopus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = WebhooksClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", + } + path = WebhooksClient.service_path(**expected) + # Check that the path construction is reversible. + actual = WebhooksClient.parse_service_path(path) + assert expected == actual + + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2004,10 +2167,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "webhook": "mussel", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = WebhooksClient.webhook_path(**expected) @@ -2017,8 +2180,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "winkle" - + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2028,7 +2190,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = WebhooksClient.common_billing_account_path(**expected) @@ -2038,8 +2200,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" - + folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = WebhooksClient.common_folder_path(folder) assert expected == actual @@ -2047,7 +2208,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = WebhooksClient.common_folder_path(**expected) @@ -2057,8 +2218,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" - + organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = WebhooksClient.common_organization_path(organization) assert expected == actual @@ -2066,7 +2226,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = WebhooksClient.common_organization_path(**expected) @@ -2076,8 +2236,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" - + project = "scallop" expected = "projects/{project}".format(project=project,) actual = WebhooksClient.common_project_path(project) assert expected == actual @@ -2085,7 +2244,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = WebhooksClient.common_project_path(**expected) @@ -2095,9 +2254,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" - + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2107,8 +2265,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = WebhooksClient.common_location_path(**expected) @@ -2124,7 +2282,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.WebhooksTransport, "_prep_wrapped_messages" ) as prep: client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2133,6 +2291,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = WebhooksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py b/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py index 2bfea055..ee7559ef 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsAsyncClient 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 ( + _API_CORE_VERSION, +) +from google.cloud.dialogflowcx_v3beta1.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflowcx_v3beta1.types import agent from google.cloud.dialogflowcx_v3beta1.types import agent as gcdc_agent from google.cloud.dialogflowcx_v3beta1.types import flow from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_agents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AgentsClient, AgentsAsyncClient,]) def test_agents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -146,7 +175,7 @@ def test_agents_client_get_transport_class(): def test_agents_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(AgentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -418,7 +447,7 @@ def test_agents_client_client_options_from_dict(): def test_list_agents(transport: str = "grpc", request_type=agent.ListAgentsRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -431,19 +460,15 @@ def test_list_agents(transport: str = "grpc", request_type=agent.ListAgentsReque call.return_value = agent.ListAgentsResponse( next_page_token="next_page_token_value", ) - response = client.list_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -455,7 +480,7 @@ def test_list_agents_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -463,7 +488,6 @@ def test_list_agents_empty_call(): client.list_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() @@ -472,7 +496,7 @@ async def test_list_agents_async( transport: str = "grpc_asyncio", request_type=agent.ListAgentsRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -485,18 +509,15 @@ async def test_list_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.ListAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_agents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ListAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -506,17 +527,17 @@ async def test_list_agents_async_from_dict(): def test_list_agents_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ListAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: call.return_value = agent.ListAgentsResponse() - client.list_agents(request) # Establish that the underlying gRPC stub method was called. @@ -531,11 +552,12 @@ def test_list_agents_field_headers(): @pytest.mark.asyncio async def test_list_agents_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ListAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ async def test_list_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.ListAgentsResponse() ) - await client.list_agents(request) # Establish that the underlying gRPC stub method was called. @@ -557,13 +578,12 @@ async def test_list_agents_field_headers_async(): def test_list_agents_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.ListAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_agents(parent="parent_value",) @@ -572,12 +592,11 @@ def test_list_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_agents_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -589,7 +608,7 @@ def test_list_agents_flattened_error(): @pytest.mark.asyncio async def test_list_agents_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -607,13 +626,12 @@ async def test_list_agents_flattened_async(): # 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_agents_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -624,7 +642,7 @@ async def test_list_agents_flattened_error_async(): def test_list_agents_pager(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -654,7 +672,7 @@ def test_list_agents_pager(): def test_list_agents_pages(): - client = AgentsClient(credentials=credentials.AnonymousCredentials,) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_agents), "__call__") as call: @@ -676,7 +694,7 @@ def test_list_agents_pages(): @pytest.mark.asyncio async def test_list_agents_async_pager(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,7 +723,7 @@ async def test_list_agents_async_pager(): @pytest.mark.asyncio async def test_list_agents_async_pages(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -731,7 +749,7 @@ async def test_list_agents_async_pages(): def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -745,6 +763,7 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -753,37 +772,25 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -795,7 +802,7 @@ def test_get_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -803,7 +810,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -812,7 +818,7 @@ async def test_get_agent_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -827,6 +833,7 @@ async def test_get_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -836,36 +843,25 @@ async def test_get_agent_async( enable_spell_correction=True, ) ) - response = await client.get_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -875,17 +871,17 @@ async def test_get_agent_async_from_dict(): def test_get_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.GetAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = agent.Agent() - client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -900,17 +896,17 @@ def test_get_agent_field_headers(): @pytest.mark.asyncio async def test_get_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.GetAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) - await client.get_agent(request) # Establish that the underlying gRPC stub method was called. @@ -924,13 +920,12 @@ async def test_get_agent_field_headers_async(): def test_get_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent(name="name_value",) @@ -939,12 +934,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +950,7 @@ def test_get_agent_flattened_error(): @pytest.mark.asyncio async def test_get_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_agent), "__call__") as call: @@ -972,13 +966,12 @@ async def test_get_agent_flattened_async(): # 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_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -992,7 +985,7 @@ def test_create_agent( transport: str = "grpc", request_type=gcdc_agent.CreateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1006,6 +999,7 @@ def test_create_agent( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1014,37 +1008,25 @@ def test_create_agent( enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.create_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1056,7 +1038,7 @@ def test_create_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1064,7 +1046,6 @@ def test_create_agent_empty_call(): client.create_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() @@ -1073,7 +1054,7 @@ async def test_create_agent_async( transport: str = "grpc_asyncio", request_type=gcdc_agent.CreateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1088,6 +1069,7 @@ async def test_create_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1097,36 +1079,25 @@ async def test_create_agent_async( enable_spell_correction=True, ) ) - response = await client.create_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.CreateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1136,17 +1107,17 @@ async def test_create_agent_async_from_dict(): def test_create_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = gcdc_agent.CreateAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: call.return_value = gcdc_agent.Agent() - client.create_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1161,17 +1132,17 @@ def test_create_agent_field_headers(): @pytest.mark.asyncio async def test_create_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = gcdc_agent.CreateAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.create_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1185,13 +1156,12 @@ async def test_create_agent_field_headers_async(): def test_create_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_agent( @@ -1202,14 +1172,12 @@ def test_create_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].agent == gcdc_agent.Agent(name="name_value") def test_create_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1223,7 +1191,7 @@ def test_create_agent_flattened_error(): @pytest.mark.asyncio async def test_create_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_agent), "__call__") as call: @@ -1241,15 +1209,13 @@ async def test_create_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].agent == gcdc_agent.Agent(name="name_value") @pytest.mark.asyncio async def test_create_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1265,7 +1231,7 @@ def test_update_agent( transport: str = "grpc", request_type=gcdc_agent.UpdateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1279,6 +1245,7 @@ def test_update_agent( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1287,37 +1254,25 @@ def test_update_agent( enable_stackdriver_logging=True, enable_spell_correction=True, ) - response = client.update_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1329,7 +1284,7 @@ def test_update_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1337,7 +1292,6 @@ def test_update_agent_empty_call(): client.update_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() @@ -1346,7 +1300,7 @@ async def test_update_agent_async( transport: str = "grpc_asyncio", request_type=gcdc_agent.UpdateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1361,6 +1315,7 @@ async def test_update_agent_async( name="name_value", display_name="display_name_value", default_language_code="default_language_code_value", + supported_language_codes=["supported_language_codes_value"], time_zone="time_zone_value", description="description_value", avatar_uri="avatar_uri_value", @@ -1370,36 +1325,25 @@ async def test_update_agent_async( enable_spell_correction=True, ) ) - response = await client.update_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_agent.UpdateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_agent.Agent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.default_language_code == "default_language_code_value" - + assert response.supported_language_codes == ["supported_language_codes_value"] assert response.time_zone == "time_zone_value" - assert response.description == "description_value" - assert response.avatar_uri == "avatar_uri_value" - assert response.start_flow == "start_flow_value" - assert response.security_settings == "security_settings_value" - assert response.enable_stackdriver_logging is True - assert response.enable_spell_correction is True @@ -1409,17 +1353,17 @@ async def test_update_agent_async_from_dict(): def test_update_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = gcdc_agent.UpdateAgentRequest() + request.agent.name = "agent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: call.return_value = gcdc_agent.Agent() - client.update_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1434,17 +1378,17 @@ def test_update_agent_field_headers(): @pytest.mark.asyncio async def test_update_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = gcdc_agent.UpdateAgentRequest() + request.agent.name = "agent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_agent.Agent()) - await client.update_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1458,32 +1402,29 @@ async def test_update_agent_field_headers_async(): def test_update_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_agent( agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1491,13 +1432,13 @@ def test_update_agent_flattened_error(): client.update_agent( gcdc_agent.UpdateAgentRequest(), agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_agent), "__call__") as call: @@ -1509,22 +1450,20 @@ async def test_update_agent_flattened_async(): # using the keyword arguments to the method. response = await client.update_agent( agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcdc_agent.Agent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1532,13 +1471,13 @@ async def test_update_agent_flattened_error_async(): await client.update_agent( gcdc_agent.UpdateAgentRequest(), agent=gcdc_agent.Agent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1549,13 +1488,11 @@ def test_delete_agent(transport: str = "grpc", request_type=agent.DeleteAgentReq with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1570,7 +1507,7 @@ def test_delete_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1578,7 +1515,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1587,7 +1523,7 @@ async def test_delete_agent_async( transport: str = "grpc_asyncio", request_type=agent.DeleteAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1598,13 +1534,11 @@ async def test_delete_agent_async( with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() # Establish that the response is the type that we expect. @@ -1617,17 +1551,17 @@ async def test_delete_agent_async_from_dict(): def test_delete_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.DeleteAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = None - client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1642,17 +1576,17 @@ def test_delete_agent_field_headers(): @pytest.mark.asyncio async def test_delete_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.DeleteAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1666,13 +1600,12 @@ async def test_delete_agent_field_headers_async(): def test_delete_agent_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_agent(name="name_value",) @@ -1681,12 +1614,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_agent_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1698,7 +1630,7 @@ def test_delete_agent_flattened_error(): @pytest.mark.asyncio async def test_delete_agent_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: @@ -1714,13 +1646,12 @@ async def test_delete_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_agent_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1732,7 +1663,7 @@ async def test_delete_agent_flattened_error_async(): def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1743,13 +1674,11 @@ def test_export_agent(transport: str = "grpc", request_type=agent.ExportAgentReq with mock.patch.object(type(client.transport.export_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1764,7 +1693,7 @@ def test_export_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1772,7 +1701,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1781,7 +1709,7 @@ async def test_export_agent_async( transport: str = "grpc_asyncio", request_type=agent.ExportAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1794,13 +1722,11 @@ async def test_export_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() # Establish that the response is the type that we expect. @@ -1813,17 +1739,17 @@ async def test_export_agent_async_from_dict(): def test_export_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ExportAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.export_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1838,11 +1764,12 @@ def test_export_agent_field_headers(): @pytest.mark.asyncio async def test_export_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ExportAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1850,7 +1777,6 @@ async def test_export_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1865,7 +1791,7 @@ async def test_export_agent_field_headers_async(): def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentRequest): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1876,13 +1802,11 @@ def test_restore_agent(transport: str = "grpc", request_type=agent.RestoreAgentR with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -1897,7 +1821,7 @@ def test_restore_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1905,7 +1829,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -1914,7 +1837,7 @@ async def test_restore_agent_async( transport: str = "grpc_asyncio", request_type=agent.RestoreAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1927,13 +1850,11 @@ async def test_restore_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() # Establish that the response is the type that we expect. @@ -1946,17 +1867,17 @@ async def test_restore_agent_async_from_dict(): def test_restore_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.RestoreAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.restore_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1971,11 +1892,12 @@ def test_restore_agent_field_headers(): @pytest.mark.asyncio async def test_restore_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.RestoreAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1983,7 +1905,6 @@ async def test_restore_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2000,7 +1921,7 @@ def test_validate_agent( transport: str = "grpc", request_type=agent.ValidateAgentRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2011,19 +1932,15 @@ def test_validate_agent( with mock.patch.object(type(client.transport.validate_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult(name="name_value",) - response = client.validate_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2035,7 +1952,7 @@ def test_validate_agent_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2043,7 +1960,6 @@ def test_validate_agent_empty_call(): client.validate_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() @@ -2052,7 +1968,7 @@ async def test_validate_agent_async( transport: str = "grpc_asyncio", request_type=agent.ValidateAgentRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2065,18 +1981,15 @@ async def test_validate_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult(name="name_value",) ) - response = await client.validate_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.ValidateAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2086,17 +1999,17 @@ async def test_validate_agent_async_from_dict(): def test_validate_agent_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.ValidateAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.validate_agent), "__call__") as call: call.return_value = agent.AgentValidationResult() - client.validate_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2111,11 +2024,12 @@ def test_validate_agent_field_headers(): @pytest.mark.asyncio async def test_validate_agent_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.ValidateAgentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2123,7 +2037,6 @@ async def test_validate_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult() ) - await client.validate_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2140,7 +2053,7 @@ def test_get_agent_validation_result( transport: str = "grpc", request_type=agent.GetAgentValidationResultRequest ): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2153,19 +2066,15 @@ def test_get_agent_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult(name="name_value",) - response = client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2177,7 +2086,7 @@ def test_get_agent_validation_result_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 = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2187,7 +2096,6 @@ def test_get_agent_validation_result_empty_call(): client.get_agent_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() @@ -2196,7 +2104,7 @@ async def test_get_agent_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetAgentValidationResultRequest ): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2211,18 +2119,15 @@ async def test_get_agent_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult(name="name_value",) ) - response = await client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentValidationResultRequest() # Establish that the response is the type that we expect. assert isinstance(response, agent.AgentValidationResult) - assert response.name == "name_value" @@ -2232,11 +2137,12 @@ async def test_get_agent_validation_result_async_from_dict(): def test_get_agent_validation_result_field_headers(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(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 = agent.GetAgentValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2244,7 +2150,6 @@ def test_get_agent_validation_result_field_headers(): type(client.transport.get_agent_validation_result), "__call__" ) as call: call.return_value = agent.AgentValidationResult() - client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2259,11 +2164,12 @@ def test_get_agent_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_agent_validation_result_field_headers_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(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 = agent.GetAgentValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2273,7 +2179,6 @@ async def test_get_agent_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.AgentValidationResult() ) - await client.get_agent_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2287,7 +2192,7 @@ async def test_get_agent_validation_result_field_headers_async(): def test_get_agent_validation_result_flattened(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2295,7 +2200,6 @@ def test_get_agent_validation_result_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = agent.AgentValidationResult() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_agent_validation_result(name="name_value",) @@ -2304,12 +2208,11 @@ def test_get_agent_validation_result_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_agent_validation_result_flattened_error(): - client = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2321,7 +2224,7 @@ def test_get_agent_validation_result_flattened_error(): @pytest.mark.asyncio async def test_get_agent_validation_result_flattened_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2341,13 +2244,12 @@ async def test_get_agent_validation_result_flattened_async(): # 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_agent_validation_result_flattened_error_async(): - client = AgentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2360,16 +2262,16 @@ async def test_get_agent_validation_result_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2379,7 +2281,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AgentsClient( @@ -2390,7 +2292,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AgentsClient(transport=transport) assert client.transport is transport @@ -2399,13 +2301,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AgentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AgentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2417,23 +2319,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = AgentsClient(credentials=credentials.AnonymousCredentials(),) + client = AgentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AgentsGrpcTransport,) def test_agents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2445,7 +2347,7 @@ def test_agents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AgentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2471,15 +2373,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2495,19 +2422,36 @@ def test_agents_base_transport_with_credentials_file(): def test_agents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.agents.transports.AgentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AgentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2518,14 +2462,38 @@ def test_agents_auth_adc(): ) -def test_agents_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AgentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2535,12 +2503,123 @@ def test_agents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_agents_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,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentsGrpcTransport, grpc_helpers), + (transports.AgentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_agents_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AgentsGrpcTransport, transports.AgentsGrpcAsyncIOTransport], ) def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2582,7 +2661,7 @@ def test_agents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_agents_host_no_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2592,7 +2671,7 @@ def test_agents_host_no_port(): def test_agents_host_with_port(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2643,9 +2722,9 @@ def test_agents_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2724,7 +2803,7 @@ def test_agents_transport_channel_mtls_with_adc(transport_class): def test_agents_grpc_lro_client(): client = AgentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2737,7 +2816,7 @@ def test_agents_grpc_lro_client(): def test_agents_grpc_lro_async_client(): client = AgentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2752,7 +2831,6 @@ def test_agent_path(): project = "squid" location = "clam" agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @@ -2777,7 +2855,6 @@ def test_agent_validation_result_path(): project = "cuttlefish" location = "mussel" agent = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/validationResult".format( project=project, location=location, agent=agent, ) @@ -2798,65 +2875,88 @@ def test_parse_agent_validation_result_path(): assert expected == actual -def test_flow_path(): +def test_environment_path(): project = "squid" location = "clam" agent = "whelk" - flow = "octopus" - - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( - project=project, location=location, agent=agent, flow=flow, + environment = "octopus" + expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( + project=project, location=location, agent=agent, environment=environment, ) - actual = AgentsClient.flow_path(project, location, agent, flow) + actual = AgentsClient.environment_path(project, location, agent, environment) assert expected == actual -def test_parse_flow_path(): +def test_parse_environment_path(): expected = { "project": "oyster", "location": "nudibranch", "agent": "cuttlefish", - "flow": "mussel", + "environment": "mussel", } - path = AgentsClient.flow_path(**expected) + path = AgentsClient.environment_path(**expected) # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_path(path) + actual = AgentsClient.parse_environment_path(path) assert expected == actual -def test_flow_validation_result_path(): +def test_flow_path(): project = "winkle" location = "nautilus" agent = "scallop" flow = "abalone" - - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) - actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + actual = AgentsClient.flow_path(project, location, agent, flow) assert expected == actual -def test_parse_flow_validation_result_path(): +def test_parse_flow_path(): expected = { "project": "squid", "location": "clam", "agent": "whelk", "flow": "octopus", } - path = AgentsClient.flow_validation_result_path(**expected) + path = AgentsClient.flow_path(**expected) # Check that the path construction is reversible. - actual = AgentsClient.parse_flow_validation_result_path(path) + actual = AgentsClient.parse_flow_path(path) assert expected == actual -def test_security_settings_path(): +def test_flow_validation_result_path(): project = "oyster" location = "nudibranch" - security_settings = "cuttlefish" + agent = "cuttlefish" + flow = "mussel" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( + project=project, location=location, agent=agent, flow=flow, + ) + actual = AgentsClient.flow_validation_result_path(project, location, agent, flow) + assert expected == actual + + +def test_parse_flow_validation_result_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "agent": "scallop", + "flow": "abalone", + } + path = AgentsClient.flow_validation_result_path(**expected) + + # Check that the path construction is reversible. + actual = AgentsClient.parse_flow_validation_result_path(path) + assert expected == actual + +def test_security_settings_path(): + project = "squid" + location = "clam" + security_settings = "whelk" expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @@ -2866,9 +2966,9 @@ def test_security_settings_path(): def test_parse_security_settings_path(): expected = { - "project": "mussel", - "location": "winkle", - "security_settings": "nautilus", + "project": "octopus", + "location": "oyster", + "security_settings": "nudibranch", } path = AgentsClient.security_settings_path(**expected) @@ -2878,8 +2978,7 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): - billing_account = "scallop" - + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2889,7 +2988,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "mussel", } path = AgentsClient.common_billing_account_path(**expected) @@ -2899,8 +2998,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2908,7 +3006,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "nautilus", } path = AgentsClient.common_folder_path(**expected) @@ -2918,8 +3016,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2927,7 +3024,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "abalone", } path = AgentsClient.common_organization_path(**expected) @@ -2937,8 +3034,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2946,7 +3042,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "clam", } path = AgentsClient.common_project_path(**expected) @@ -2956,9 +3052,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2968,8 +3063,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "oyster", + "location": "nudibranch", } path = AgentsClient.common_location_path(**expected) @@ -2985,7 +3080,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AgentsTransport, "_prep_wrapped_messages" ) as prep: client = AgentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2994,6 +3089,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AgentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py index db575e44..2c7b5005 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.entity_types import ( EntityTypesAsyncClient, @@ -38,10 +37,40 @@ 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_entity_types_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EntityTypesClient, EntityTypesAsyncClient,]) def test_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -153,7 +182,7 @@ def test_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -437,7 +466,7 @@ def test_list_entity_types( transport: str = "grpc", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -452,19 +481,15 @@ def test_list_entity_types( call.return_value = entity_type.ListEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -476,7 +501,7 @@ def test_list_entity_types_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -486,7 +511,6 @@ def test_list_entity_types_empty_call(): client.list_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() @@ -495,7 +519,7 @@ async def test_list_entity_types_async( transport: str = "grpc_asyncio", request_type=entity_type.ListEntityTypesRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -512,18 +536,15 @@ async def test_list_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.ListEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -533,11 +554,12 @@ async def test_list_entity_types_async_from_dict(): def test_list_entity_types_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ def test_list_entity_types_field_headers(): type(client.transport.list_entity_types), "__call__" ) as call: call.return_value = entity_type.ListEntityTypesResponse() - client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -560,11 +581,12 @@ def test_list_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_entity_types_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.ListEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -574,7 +596,6 @@ async def test_list_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.ListEntityTypesResponse() ) - await client.list_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -588,7 +609,7 @@ async def test_list_entity_types_field_headers_async(): def test_list_entity_types_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -596,7 +617,6 @@ def test_list_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = entity_type.ListEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_entity_types(parent="parent_value",) @@ -605,12 +625,11 @@ def test_list_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_entity_types_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -622,7 +641,7 @@ def test_list_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_entity_types_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -642,13 +661,12 @@ async def test_list_entity_types_flattened_async(): # 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_entity_types_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -659,7 +677,7 @@ async def test_list_entity_types_flattened_error_async(): def test_list_entity_types_pager(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -701,7 +719,7 @@ def test_list_entity_types_pager(): def test_list_entity_types_pages(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -735,7 +753,7 @@ def test_list_entity_types_pages(): @pytest.mark.asyncio async def test_list_entity_types_async_pager(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -776,7 +794,7 @@ async def test_list_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_entity_types_async_pages(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -816,7 +834,7 @@ def test_get_entity_type( transport: str = "grpc", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -834,32 +852,23 @@ def test_get_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -871,7 +880,7 @@ def test_get_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -879,7 +888,6 @@ def test_get_entity_type_empty_call(): client.get_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() @@ -888,7 +896,7 @@ async def test_get_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.GetEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -908,31 +916,23 @@ async def test_get_entity_type_async( redact=True, ) ) - response = await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.GetEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -942,17 +942,17 @@ async def test_get_entity_type_async_from_dict(): def test_get_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: call.return_value = entity_type.EntityType() - client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -967,11 +967,12 @@ def test_get_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.GetEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -979,7 +980,6 @@ async def test_get_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( entity_type.EntityType() ) - await client.get_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -993,13 +993,12 @@ async def test_get_entity_type_field_headers_async(): def test_get_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_entity_type(name="name_value",) @@ -1008,12 +1007,11 @@ def test_get_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1025,7 +1023,7 @@ def test_get_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_entity_type), "__call__") as call: @@ -1043,13 +1041,12 @@ async def test_get_entity_type_flattened_async(): # 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_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1063,7 +1060,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcdc_entity_type.CreateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1083,32 +1080,23 @@ def test_create_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1120,7 +1108,7 @@ def test_create_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1130,7 +1118,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() @@ -1140,7 +1127,7 @@ async def test_create_entity_type_async( request_type=gcdc_entity_type.CreateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1162,31 +1149,23 @@ async def test_create_entity_type_async( redact=True, ) ) - response = await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1196,11 +1175,12 @@ async def test_create_entity_type_async_from_dict(): def test_create_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = gcdc_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1208,7 +1188,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcdc_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1223,11 +1202,12 @@ def test_create_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = gcdc_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1237,7 +1217,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1251,7 +1230,7 @@ async def test_create_entity_type_field_headers_async(): def test_create_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1259,7 +1238,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_entity_type( @@ -1271,14 +1249,12 @@ def test_create_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") def test_create_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1292,7 +1268,7 @@ def test_create_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1315,15 +1291,13 @@ async def test_create_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") @pytest.mark.asyncio async def test_create_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1313,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcdc_entity_type.UpdateEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1359,32 +1333,23 @@ def test_update_entity_type( enable_fuzzy_extraction=True, redact=True, ) - response = client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1396,7 +1361,7 @@ def test_update_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1406,7 +1371,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() @@ -1416,7 +1380,7 @@ async def test_update_entity_type_async( request_type=gcdc_entity_type.UpdateEntityTypeRequest, ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1438,31 +1402,23 @@ async def test_update_entity_type_async( redact=True, ) ) - response = await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcdc_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcdc_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True - assert response.redact is True @@ -1472,11 +1428,12 @@ async def test_update_entity_type_async_from_dict(): def test_update_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = gcdc_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1484,7 +1441,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcdc_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1501,11 +1457,12 @@ def test_update_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = gcdc_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1472,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1531,7 +1487,7 @@ async def test_update_entity_type_field_headers_async(): def test_update_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1539,26 +1495,23 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_entity_type.EntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_entity_type( entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1566,13 +1519,13 @@ def test_update_entity_type_flattened_error(): client.update_entity_type( gcdc_entity_type.UpdateEntityTypeRequest(), entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1588,22 +1541,20 @@ async def test_update_entity_type_flattened_async(): # using the keyword arguments to the method. response = await client.update_entity_type( entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcdc_entity_type.EntityType(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1611,7 +1562,7 @@ async def test_update_entity_type_flattened_error_async(): await client.update_entity_type( gcdc_entity_type.UpdateEntityTypeRequest(), entity_type=gcdc_entity_type.EntityType(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1619,7 +1570,7 @@ def test_delete_entity_type( transport: str = "grpc", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1632,13 +1583,11 @@ def test_delete_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1653,7 +1602,7 @@ def test_delete_entity_type_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 = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1663,7 +1612,6 @@ def test_delete_entity_type_empty_call(): client.delete_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() @@ -1672,7 +1620,7 @@ async def test_delete_entity_type_async( transport: str = "grpc_asyncio", request_type=entity_type.DeleteEntityTypeRequest ): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1685,13 +1633,11 @@ async def test_delete_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.DeleteEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1704,11 +1650,12 @@ async def test_delete_entity_type_async_from_dict(): def test_delete_entity_type_field_headers(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(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 = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1716,7 +1663,6 @@ def test_delete_entity_type_field_headers(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = None - client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1731,11 +1677,12 @@ def test_delete_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_entity_type_field_headers_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(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 = entity_type.DeleteEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1743,7 +1690,6 @@ async def test_delete_entity_type_field_headers_async(): type(client.transport.delete_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1757,7 +1703,7 @@ async def test_delete_entity_type_field_headers_async(): def test_delete_entity_type_flattened(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1765,7 +1711,6 @@ def test_delete_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_entity_type(name="name_value",) @@ -1774,12 +1719,11 @@ def test_delete_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_entity_type_flattened_error(): - client = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1791,7 +1735,7 @@ def test_delete_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_entity_type_flattened_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1809,13 +1753,12 @@ async def test_delete_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_entity_type_flattened_error_async(): - client = EntityTypesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1828,16 +1771,16 @@ async def test_delete_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -1847,7 +1790,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EntityTypesClient( @@ -1858,7 +1801,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EntityTypesClient(transport=transport) assert client.transport is transport @@ -1867,13 +1810,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1885,23 +1828,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = EntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = EntityTypesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EntityTypesGrpcTransport,) def test_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1913,7 +1856,7 @@ def test_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1930,15 +1873,40 @@ def test_entity_types_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1954,19 +1922,36 @@ def test_entity_types_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EntityTypesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1977,14 +1962,38 @@ def test_entity_types_auth_adc(): ) -def test_entity_types_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1994,12 +2003,127 @@ def test_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_entity_types_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,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EntityTypesGrpcTransport, grpc_helpers), + (transports.EntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_entity_types_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EntityTypesGrpcTransport, transports.EntityTypesGrpcAsyncIOTransport], ) def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2041,7 +2165,7 @@ def test_entity_types_grpc_transport_client_cert_source_for_mtls(transport_class def test_entity_types_host_no_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2051,7 +2175,7 @@ def test_entity_types_host_no_port(): def test_entity_types_host_with_port(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2102,9 +2226,9 @@ def test_entity_types_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2186,7 +2310,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -2210,7 +2333,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2231,7 +2353,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2250,7 +2371,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2269,7 +2389,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -2289,7 +2408,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2316,7 +2434,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2325,6 +2443,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py index 5a7045e1..44ff5fbf 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_environments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.environments import ( EnvironmentsAsyncClient, @@ -41,13 +40,43 @@ 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 ( + _API_CORE_VERSION, +) +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 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -93,7 +122,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -108,7 +137,7 @@ def test_environments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [EnvironmentsClient, EnvironmentsAsyncClient,]) def test_environments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -159,7 +188,7 @@ def test_environments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(EnvironmentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -443,7 +472,7 @@ def test_list_environments( transport: str = "grpc", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -458,19 +487,15 @@ def test_list_environments( call.return_value = environment.ListEnvironmentsResponse( next_page_token="next_page_token_value", ) - response = client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEnvironmentsPager) - assert response.next_page_token == "next_page_token_value" @@ -482,7 +507,7 @@ def test_list_environments_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -492,7 +517,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -501,7 +525,7 @@ async def test_list_environments_async( transport: str = "grpc_asyncio", request_type=environment.ListEnvironmentsRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -518,18 +542,15 @@ async def test_list_environments_async( next_page_token="next_page_token_value", ) ) - response = await client.list_environments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnvironmentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -539,11 +560,12 @@ async def test_list_environments_async_from_dict(): def test_list_environments_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -551,7 +573,6 @@ def test_list_environments_field_headers(): type(client.transport.list_environments), "__call__" ) as call: call.return_value = environment.ListEnvironmentsResponse() - client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -566,11 +587,12 @@ def test_list_environments_field_headers(): @pytest.mark.asyncio async def test_list_environments_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.ListEnvironmentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -580,7 +602,6 @@ async def test_list_environments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.ListEnvironmentsResponse() ) - await client.list_environments(request) # Establish that the underlying gRPC stub method was called. @@ -594,7 +615,7 @@ async def test_list_environments_field_headers_async(): def test_list_environments_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -602,7 +623,6 @@ def test_list_environments_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = environment.ListEnvironmentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_environments(parent="parent_value",) @@ -611,12 +631,11 @@ def test_list_environments_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_environments_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -628,7 +647,7 @@ def test_list_environments_flattened_error(): @pytest.mark.asyncio async def test_list_environments_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -648,13 +667,12 @@ async def test_list_environments_flattened_async(): # 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_environments_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -665,7 +683,7 @@ async def test_list_environments_flattened_error_async(): def test_list_environments_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -707,7 +725,7 @@ def test_list_environments_pager(): def test_list_environments_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -741,7 +759,7 @@ def test_list_environments_pages(): @pytest.mark.asyncio async def test_list_environments_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -782,7 +800,7 @@ async def test_list_environments_async_pager(): @pytest.mark.asyncio async def test_list_environments_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -822,7 +840,7 @@ def test_get_environment( transport: str = "grpc", request_type=environment.GetEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -837,23 +855,17 @@ def test_get_environment( display_name="display_name_value", description="description_value", ) - response = client.get_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, environment.Environment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -865,7 +877,7 @@ def test_get_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -873,7 +885,6 @@ def test_get_environment_empty_call(): client.get_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() @@ -882,7 +893,7 @@ async def test_get_environment_async( transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -899,22 +910,17 @@ async def test_get_environment_async( description="description_value", ) ) - response = await client.get_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.GetEnvironmentRequest() # Establish that the response is the type that we expect. assert isinstance(response, environment.Environment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" @@ -924,17 +930,17 @@ async def test_get_environment_async_from_dict(): def test_get_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.GetEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: call.return_value = environment.Environment() - client.get_environment(request) # Establish that the underlying gRPC stub method was called. @@ -949,11 +955,12 @@ def test_get_environment_field_headers(): @pytest.mark.asyncio async def test_get_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.GetEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -961,7 +968,6 @@ async def test_get_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.Environment() ) - await client.get_environment(request) # Establish that the underlying gRPC stub method was called. @@ -975,13 +981,12 @@ async def test_get_environment_field_headers_async(): def test_get_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = environment.Environment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_environment(name="name_value",) @@ -990,12 +995,11 @@ def test_get_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1007,7 +1011,7 @@ def test_get_environment_flattened_error(): @pytest.mark.asyncio async def test_get_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_environment), "__call__") as call: @@ -1025,13 +1029,12 @@ async def test_get_environment_flattened_async(): # 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_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1045,7 +1048,7 @@ def test_create_environment( transport: str = "grpc", request_type=gcdc_environment.CreateEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1058,13 +1061,11 @@ def test_create_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1079,7 +1080,7 @@ def test_create_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1089,7 +1090,6 @@ def test_create_environment_empty_call(): client.create_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() @@ -1099,7 +1099,7 @@ async def test_create_environment_async( request_type=gcdc_environment.CreateEnvironmentRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1114,13 +1114,11 @@ async def test_create_environment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.CreateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1133,11 +1131,12 @@ async def test_create_environment_async_from_dict(): def test_create_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.CreateEnvironmentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1145,7 +1144,6 @@ def test_create_environment_field_headers(): type(client.transport.create_environment), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1160,11 +1158,12 @@ def test_create_environment_field_headers(): @pytest.mark.asyncio async def test_create_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.CreateEnvironmentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1174,7 +1173,6 @@ async def test_create_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1188,7 +1186,7 @@ async def test_create_environment_field_headers_async(): def test_create_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1196,7 +1194,6 @@ def test_create_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_environment( @@ -1208,14 +1205,12 @@ def test_create_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].environment == gcdc_environment.Environment(name="name_value") def test_create_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1229,7 +1224,7 @@ def test_create_environment_flattened_error(): @pytest.mark.asyncio async def test_create_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1252,15 +1247,13 @@ async def test_create_environment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].environment == gcdc_environment.Environment(name="name_value") @pytest.mark.asyncio async def test_create_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1276,7 +1269,7 @@ def test_update_environment( transport: str = "grpc", request_type=gcdc_environment.UpdateEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1289,13 +1282,11 @@ def test_update_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1310,7 +1301,7 @@ def test_update_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1320,7 +1311,6 @@ def test_update_environment_empty_call(): client.update_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() @@ -1330,7 +1320,7 @@ async def test_update_environment_async( request_type=gcdc_environment.UpdateEnvironmentRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1345,13 +1335,11 @@ async def test_update_environment_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_environment.UpdateEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1364,11 +1352,12 @@ async def test_update_environment_async_from_dict(): def test_update_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.UpdateEnvironmentRequest() + request.environment.name = "environment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1376,7 +1365,6 @@ def test_update_environment_field_headers(): type(client.transport.update_environment), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1393,11 +1381,12 @@ def test_update_environment_field_headers(): @pytest.mark.asyncio async def test_update_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcdc_environment.UpdateEnvironmentRequest() + request.environment.name = "environment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1407,7 +1396,6 @@ async def test_update_environment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1423,7 +1411,7 @@ async def test_update_environment_field_headers_async(): def test_update_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1431,26 +1419,23 @@ def test_update_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_environment( environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].environment == gcdc_environment.Environment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1458,13 +1443,13 @@ def test_update_environment_flattened_error(): client.update_environment( gcdc_environment.UpdateEnvironmentRequest(), environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1480,22 +1465,20 @@ async def test_update_environment_flattened_async(): # using the keyword arguments to the method. response = await client.update_environment( environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].environment == gcdc_environment.Environment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1503,7 +1486,7 @@ async def test_update_environment_flattened_error_async(): await client.update_environment( gcdc_environment.UpdateEnvironmentRequest(), environment=gcdc_environment.Environment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1511,7 +1494,7 @@ def test_delete_environment( transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1524,13 +1507,11 @@ def test_delete_environment( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1545,7 +1526,7 @@ def test_delete_environment_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1555,7 +1536,6 @@ def test_delete_environment_empty_call(): client.delete_environment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() @@ -1564,7 +1544,7 @@ async def test_delete_environment_async( transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1577,13 +1557,11 @@ async def test_delete_environment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_environment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.DeleteEnvironmentRequest() # Establish that the response is the type that we expect. @@ -1596,11 +1574,12 @@ async def test_delete_environment_async_from_dict(): def test_delete_environment_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.DeleteEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1608,7 +1587,6 @@ def test_delete_environment_field_headers(): type(client.transport.delete_environment), "__call__" ) as call: call.return_value = None - client.delete_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1623,11 +1601,12 @@ def test_delete_environment_field_headers(): @pytest.mark.asyncio async def test_delete_environment_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.DeleteEnvironmentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1635,7 +1614,6 @@ async def test_delete_environment_field_headers_async(): type(client.transport.delete_environment), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_environment(request) # Establish that the underlying gRPC stub method was called. @@ -1649,7 +1627,7 @@ async def test_delete_environment_field_headers_async(): def test_delete_environment_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1657,7 +1635,6 @@ def test_delete_environment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_environment(name="name_value",) @@ -1666,12 +1643,11 @@ def test_delete_environment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_environment_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1683,7 +1659,7 @@ def test_delete_environment_flattened_error(): @pytest.mark.asyncio async def test_delete_environment_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1701,13 +1677,12 @@ async def test_delete_environment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_environment_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1721,7 +1696,7 @@ def test_lookup_environment_history( transport: str = "grpc", request_type=environment.LookupEnvironmentHistoryRequest ): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1736,19 +1711,15 @@ def test_lookup_environment_history( call.return_value = environment.LookupEnvironmentHistoryResponse( next_page_token="next_page_token_value", ) - response = client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.LookupEnvironmentHistoryPager) - assert response.next_page_token == "next_page_token_value" @@ -1760,7 +1731,7 @@ def test_lookup_environment_history_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1770,7 +1741,6 @@ def test_lookup_environment_history_empty_call(): client.lookup_environment_history() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() @@ -1780,7 +1750,7 @@ async def test_lookup_environment_history_async( request_type=environment.LookupEnvironmentHistoryRequest, ): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1797,18 +1767,15 @@ async def test_lookup_environment_history_async( next_page_token="next_page_token_value", ) ) - response = await client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == environment.LookupEnvironmentHistoryRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.LookupEnvironmentHistoryAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1818,11 +1785,12 @@ async def test_lookup_environment_history_async_from_dict(): def test_lookup_environment_history_field_headers(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.LookupEnvironmentHistoryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1830,7 +1798,6 @@ def test_lookup_environment_history_field_headers(): type(client.transport.lookup_environment_history), "__call__" ) as call: call.return_value = environment.LookupEnvironmentHistoryResponse() - client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. @@ -1845,11 +1812,12 @@ def test_lookup_environment_history_field_headers(): @pytest.mark.asyncio async def test_lookup_environment_history_field_headers_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = environment.LookupEnvironmentHistoryRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1859,7 +1827,6 @@ async def test_lookup_environment_history_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( environment.LookupEnvironmentHistoryResponse() ) - await client.lookup_environment_history(request) # Establish that the underlying gRPC stub method was called. @@ -1873,7 +1840,7 @@ async def test_lookup_environment_history_field_headers_async(): def test_lookup_environment_history_flattened(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1881,7 +1848,6 @@ def test_lookup_environment_history_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = environment.LookupEnvironmentHistoryResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.lookup_environment_history(name="name_value",) @@ -1890,12 +1856,11 @@ def test_lookup_environment_history_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_lookup_environment_history_flattened_error(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1907,7 +1872,7 @@ def test_lookup_environment_history_flattened_error(): @pytest.mark.asyncio async def test_lookup_environment_history_flattened_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1927,13 +1892,12 @@ async def test_lookup_environment_history_flattened_async(): # 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_lookup_environment_history_flattened_error_async(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1944,7 +1908,7 @@ async def test_lookup_environment_history_flattened_error_async(): def test_lookup_environment_history_pager(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1986,7 +1950,7 @@ def test_lookup_environment_history_pager(): def test_lookup_environment_history_pages(): - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2020,7 +1984,7 @@ def test_lookup_environment_history_pages(): @pytest.mark.asyncio async def test_lookup_environment_history_async_pager(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2061,7 +2025,7 @@ async def test_lookup_environment_history_async_pager(): @pytest.mark.asyncio async def test_lookup_environment_history_async_pages(): - client = EnvironmentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2100,16 +2064,16 @@ async def test_lookup_environment_history_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( @@ -2119,7 +2083,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = EnvironmentsClient( @@ -2130,7 +2094,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = EnvironmentsClient(transport=transport) assert client.transport is transport @@ -2139,13 +2103,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2160,23 +2124,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) def test_environments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2188,7 +2152,7 @@ def test_environments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2211,15 +2175,40 @@ 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( - auth, "load_credentials_from_file" + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EnvironmentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2235,19 +2224,36 @@ def test_environments_base_transport_with_credentials_file(): def test_environments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EnvironmentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2258,14 +2264,44 @@ def test_environments_auth_adc(): ) -def test_environments_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2275,12 +2311,127 @@ def test_environments_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_environments_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,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EnvironmentsGrpcTransport, grpc_helpers), + (transports.EnvironmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_environments_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], ) def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2322,7 +2473,7 @@ def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class def test_environments_host_no_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2332,7 +2483,7 @@ def test_environments_host_no_port(): def test_environments_host_with_port(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2383,9 +2534,9 @@ def test_environments_transport_channel_mtls_with_client_cert_source(transport_c mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2464,7 +2615,7 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environments_grpc_lro_client(): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2477,7 +2628,7 @@ def test_environments_grpc_lro_client(): def test_environments_grpc_lro_async_client(): client = EnvironmentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2493,7 +2644,6 @@ def test_environment_path(): location = "clam" agent = "whelk" environment = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @@ -2521,7 +2671,6 @@ def test_version_path(): agent = "scallop" flow = "abalone" version = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2546,7 +2695,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2567,7 +2715,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -2586,7 +2733,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -2605,7 +2751,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -2625,7 +2770,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2652,7 +2796,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.EnvironmentsTransport, "_prep_wrapped_messages" ) as prep: client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2661,6 +2805,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = EnvironmentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py index f153fb3e..73adc4d8 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_experiments.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.experiments import ( ExperimentsAsyncClient, @@ -38,12 +37,42 @@ 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -89,7 +118,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient,]) def test_experiments_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -104,7 +133,7 @@ def test_experiments_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ExperimentsClient, ExperimentsAsyncClient,]) def test_experiments_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -155,7 +184,7 @@ def test_experiments_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ExperimentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -439,7 +468,7 @@ def test_list_experiments( transport: str = "grpc", request_type=experiment.ListExperimentsRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -452,19 +481,15 @@ def test_list_experiments( call.return_value = experiment.ListExperimentsResponse( next_page_token="next_page_token_value", ) - response = client.list_experiments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListExperimentsPager) - assert response.next_page_token == "next_page_token_value" @@ -476,7 +501,7 @@ def test_list_experiments_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -484,7 +509,6 @@ def test_list_experiments_empty_call(): client.list_experiments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() @@ -493,7 +517,7 @@ async def test_list_experiments_async( transport: str = "grpc_asyncio", request_type=experiment.ListExperimentsRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -506,18 +530,15 @@ async def test_list_experiments_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.ListExperimentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_experiments(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.ListExperimentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListExperimentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -527,17 +548,17 @@ async def test_list_experiments_async_from_dict(): def test_list_experiments_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: call.return_value = experiment.ListExperimentsResponse() - client.list_experiments(request) # Establish that the underlying gRPC stub method was called. @@ -552,11 +573,12 @@ def test_list_experiments_field_headers(): @pytest.mark.asyncio async def test_list_experiments_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.ListExperimentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -564,7 +586,6 @@ async def test_list_experiments_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.ListExperimentsResponse() ) - await client.list_experiments(request) # Establish that the underlying gRPC stub method was called. @@ -578,13 +599,12 @@ async def test_list_experiments_field_headers_async(): def test_list_experiments_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.ListExperimentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_experiments(parent="parent_value",) @@ -593,12 +613,11 @@ def test_list_experiments_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_experiments_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -610,7 +629,7 @@ def test_list_experiments_flattened_error(): @pytest.mark.asyncio async def test_list_experiments_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -628,13 +647,12 @@ async def test_list_experiments_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_experiments_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -645,7 +663,7 @@ async def test_list_experiments_flattened_error_async(): def test_list_experiments_pager(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -683,7 +701,7 @@ def test_list_experiments_pager(): def test_list_experiments_pages(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_experiments), "__call__") as call: @@ -713,7 +731,7 @@ def test_list_experiments_pages(): @pytest.mark.asyncio async def test_list_experiments_async_pager(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -750,7 +768,7 @@ async def test_list_experiments_async_pager(): @pytest.mark.asyncio async def test_list_experiments_async_pages(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -786,7 +804,7 @@ def test_get_experiment( transport: str = "grpc", request_type=experiment.GetExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -802,25 +820,18 @@ def test_get_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.get_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -832,7 +843,7 @@ def test_get_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -840,7 +851,6 @@ def test_get_experiment_empty_call(): client.get_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() @@ -849,7 +859,7 @@ async def test_get_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.GetExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -867,24 +877,18 @@ async def test_get_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.get_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.GetExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -894,17 +898,17 @@ async def test_get_experiment_async_from_dict(): def test_get_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.GetExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.get_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -919,11 +923,12 @@ def test_get_experiment_field_headers(): @pytest.mark.asyncio async def test_get_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.GetExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -931,7 +936,6 @@ async def test_get_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.get_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -945,13 +949,12 @@ async def test_get_experiment_field_headers_async(): def test_get_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_experiment(name="name_value",) @@ -960,12 +963,11 @@ def test_get_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -977,7 +979,7 @@ def test_get_experiment_flattened_error(): @pytest.mark.asyncio async def test_get_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_experiment), "__call__") as call: @@ -995,13 +997,12 @@ async def test_get_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1015,7 +1016,7 @@ def test_create_experiment( transport: str = "grpc", request_type=gcdc_experiment.CreateExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1033,25 +1034,18 @@ def test_create_experiment( description="description_value", state=gcdc_experiment.Experiment.State.DRAFT, ) - response = client.create_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1063,7 +1057,7 @@ def test_create_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1073,7 +1067,6 @@ def test_create_experiment_empty_call(): client.create_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() @@ -1083,7 +1076,7 @@ async def test_create_experiment_async( request_type=gcdc_experiment.CreateExperimentRequest, ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1103,24 +1096,18 @@ async def test_create_experiment_async( state=gcdc_experiment.Experiment.State.DRAFT, ) ) - response = await client.create_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.CreateExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1130,11 +1117,12 @@ async def test_create_experiment_async_from_dict(): def test_create_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1142,7 +1130,6 @@ def test_create_experiment_field_headers(): type(client.transport.create_experiment), "__call__" ) as call: call.return_value = gcdc_experiment.Experiment() - client.create_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1157,11 +1144,12 @@ def test_create_experiment_field_headers(): @pytest.mark.asyncio async def test_create_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = gcdc_experiment.CreateExperimentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1171,7 +1159,6 @@ async def test_create_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_experiment.Experiment() ) - await client.create_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1185,7 +1172,7 @@ async def test_create_experiment_field_headers_async(): def test_create_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1193,7 +1180,6 @@ def test_create_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_experiment( @@ -1205,14 +1191,12 @@ def test_create_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") def test_create_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1226,7 +1210,7 @@ def test_create_experiment_flattened_error(): @pytest.mark.asyncio async def test_create_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1249,15 +1233,13 @@ async def test_create_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") @pytest.mark.asyncio async def test_create_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1273,7 +1255,7 @@ def test_update_experiment( transport: str = "grpc", request_type=gcdc_experiment.UpdateExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1291,25 +1273,18 @@ def test_update_experiment( description="description_value", state=gcdc_experiment.Experiment.State.DRAFT, ) - response = client.update_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1321,7 +1296,7 @@ def test_update_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1331,7 +1306,6 @@ def test_update_experiment_empty_call(): client.update_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() @@ -1341,7 +1315,7 @@ async def test_update_experiment_async( request_type=gcdc_experiment.UpdateExperimentRequest, ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1361,24 +1335,18 @@ async def test_update_experiment_async( state=gcdc_experiment.Experiment.State.DRAFT, ) ) - response = await client.update_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_experiment.UpdateExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_experiment.Experiment.State.DRAFT @@ -1388,11 +1356,12 @@ async def test_update_experiment_async_from_dict(): def test_update_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1400,7 +1369,6 @@ def test_update_experiment_field_headers(): type(client.transport.update_experiment), "__call__" ) as call: call.return_value = gcdc_experiment.Experiment() - client.update_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1417,11 +1385,12 @@ def test_update_experiment_field_headers(): @pytest.mark.asyncio async def test_update_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = gcdc_experiment.UpdateExperimentRequest() + request.experiment.name = "experiment.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1431,7 +1400,6 @@ async def test_update_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_experiment.Experiment() ) - await client.update_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1447,7 +1415,7 @@ async def test_update_experiment_field_headers_async(): def test_update_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1455,26 +1423,23 @@ def test_update_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_experiment( experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1482,13 +1447,13 @@ def test_update_experiment_flattened_error(): client.update_experiment( gcdc_experiment.UpdateExperimentRequest(), experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1504,22 +1469,20 @@ async def test_update_experiment_flattened_async(): # using the keyword arguments to the method. response = await client.update_experiment( experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].experiment == gcdc_experiment.Experiment(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1527,7 +1490,7 @@ async def test_update_experiment_flattened_error_async(): await client.update_experiment( gcdc_experiment.UpdateExperimentRequest(), experiment=gcdc_experiment.Experiment(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1535,7 +1498,7 @@ def test_delete_experiment( transport: str = "grpc", request_type=experiment.DeleteExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1548,13 +1511,11 @@ def test_delete_experiment( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() # Establish that the response is the type that we expect. @@ -1569,7 +1530,7 @@ def test_delete_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1579,7 +1540,6 @@ def test_delete_experiment_empty_call(): client.delete_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() @@ -1588,7 +1548,7 @@ async def test_delete_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.DeleteExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1601,13 +1561,11 @@ async def test_delete_experiment_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.DeleteExperimentRequest() # Establish that the response is the type that we expect. @@ -1620,11 +1578,12 @@ async def test_delete_experiment_async_from_dict(): def test_delete_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.DeleteExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1632,7 +1591,6 @@ def test_delete_experiment_field_headers(): type(client.transport.delete_experiment), "__call__" ) as call: call.return_value = None - client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1647,11 +1605,12 @@ def test_delete_experiment_field_headers(): @pytest.mark.asyncio async def test_delete_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.DeleteExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1659,7 +1618,6 @@ async def test_delete_experiment_field_headers_async(): type(client.transport.delete_experiment), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1673,7 +1631,7 @@ async def test_delete_experiment_field_headers_async(): def test_delete_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1681,7 +1639,6 @@ def test_delete_experiment_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_experiment(name="name_value",) @@ -1690,12 +1647,11 @@ def test_delete_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1707,7 +1663,7 @@ def test_delete_experiment_flattened_error(): @pytest.mark.asyncio async def test_delete_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1725,13 +1681,12 @@ async def test_delete_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1745,7 +1700,7 @@ def test_start_experiment( transport: str = "grpc", request_type=experiment.StartExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1761,25 +1716,18 @@ def test_start_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.start_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -1791,7 +1739,7 @@ def test_start_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1799,7 +1747,6 @@ def test_start_experiment_empty_call(): client.start_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() @@ -1808,7 +1755,7 @@ async def test_start_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.StartExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1826,24 +1773,18 @@ async def test_start_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.start_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StartExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -1853,17 +1794,17 @@ async def test_start_experiment_async_from_dict(): def test_start_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.StartExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.start_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1878,11 +1819,12 @@ def test_start_experiment_field_headers(): @pytest.mark.asyncio async def test_start_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.StartExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1890,7 +1832,6 @@ async def test_start_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.start_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -1904,13 +1845,12 @@ async def test_start_experiment_field_headers_async(): def test_start_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.start_experiment(name="name_value",) @@ -1919,12 +1859,11 @@ def test_start_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_start_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1936,7 +1875,7 @@ def test_start_experiment_flattened_error(): @pytest.mark.asyncio async def test_start_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.start_experiment), "__call__") as call: @@ -1954,13 +1893,12 @@ async def test_start_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_start_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1974,7 +1912,7 @@ def test_stop_experiment( transport: str = "grpc", request_type=experiment.StopExperimentRequest ): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1990,25 +1928,18 @@ def test_stop_experiment( description="description_value", state=experiment.Experiment.State.DRAFT, ) - response = client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -2020,7 +1951,7 @@ def test_stop_experiment_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 = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2028,7 +1959,6 @@ def test_stop_experiment_empty_call(): client.stop_experiment() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() @@ -2037,7 +1967,7 @@ async def test_stop_experiment_async( transport: str = "grpc_asyncio", request_type=experiment.StopExperimentRequest ): client = ExperimentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2055,24 +1985,18 @@ async def test_stop_experiment_async( state=experiment.Experiment.State.DRAFT, ) ) - response = await client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == experiment.StopExperimentRequest() # Establish that the response is the type that we expect. assert isinstance(response, experiment.Experiment) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == experiment.Experiment.State.DRAFT @@ -2082,17 +2006,17 @@ async def test_stop_experiment_async_from_dict(): def test_stop_experiment_field_headers(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(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 = experiment.StopExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: call.return_value = experiment.Experiment() - client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -2107,11 +2031,12 @@ def test_stop_experiment_field_headers(): @pytest.mark.asyncio async def test_stop_experiment_field_headers_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(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 = experiment.StopExperimentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2119,7 +2044,6 @@ async def test_stop_experiment_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( experiment.Experiment() ) - await client.stop_experiment(request) # Establish that the underlying gRPC stub method was called. @@ -2133,13 +2057,12 @@ async def test_stop_experiment_field_headers_async(): def test_stop_experiment_flattened(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = experiment.Experiment() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.stop_experiment(name="name_value",) @@ -2148,12 +2071,11 @@ def test_stop_experiment_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_stop_experiment_flattened_error(): - client = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2165,7 +2087,7 @@ def test_stop_experiment_flattened_error(): @pytest.mark.asyncio async def test_stop_experiment_flattened_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.stop_experiment), "__call__") as call: @@ -2183,13 +2105,12 @@ async def test_stop_experiment_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_stop_experiment_flattened_error_async(): - client = ExperimentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2202,16 +2123,16 @@ async def test_stop_experiment_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( @@ -2221,7 +2142,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ExperimentsClient( @@ -2232,7 +2153,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ExperimentsClient(transport=transport) assert client.transport is transport @@ -2241,13 +2162,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ExperimentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ExperimentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2259,23 +2180,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = ExperimentsClient(credentials=credentials.AnonymousCredentials(),) + client = ExperimentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ExperimentsGrpcTransport,) def test_experiments_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ExperimentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2287,7 +2208,7 @@ def test_experiments_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ExperimentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2306,15 +2227,40 @@ def test_experiments_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2330,19 +2276,36 @@ def test_experiments_base_transport_with_credentials_file(): def test_experiments_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.experiments.transports.ExperimentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ExperimentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2353,14 +2316,38 @@ def test_experiments_auth_adc(): ) -def test_experiments_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.ExperimentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2370,12 +2357,127 @@ def test_experiments_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_experiments_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,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ExperimentsGrpcTransport, grpc_helpers), + (transports.ExperimentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_experiments_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.ExperimentsGrpcTransport, transports.ExperimentsGrpcAsyncIOTransport], ) def test_experiments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2417,7 +2519,7 @@ def test_experiments_grpc_transport_client_cert_source_for_mtls(transport_class) def test_experiments_host_no_port(): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2427,7 +2529,7 @@ def test_experiments_host_no_port(): def test_experiments_host_with_port(): client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2478,9 +2580,9 @@ def test_experiments_transport_channel_mtls_with_client_cert_source(transport_cl mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2563,7 +2665,6 @@ def test_experiment_path(): agent = "whelk" environment = "octopus" experiment = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}/experiments/{experiment}".format( project=project, location=location, @@ -2598,7 +2699,6 @@ def test_version_path(): agent = "squid" flow = "clam" version = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2623,7 +2723,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2644,7 +2743,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = ExperimentsClient.common_folder_path(folder) assert expected == actual @@ -2663,7 +2761,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = ExperimentsClient.common_organization_path(organization) assert expected == actual @@ -2682,7 +2779,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = ExperimentsClient.common_project_path(project) assert expected == actual @@ -2702,7 +2798,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2729,7 +2824,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ExperimentsTransport, "_prep_wrapped_messages" ) as prep: client = ExperimentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2738,6 +2833,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ExperimentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py index a3fc79d3..a728506a 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_flows.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,27 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.flows import FlowsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 @@ -47,9 +52,33 @@ from google.cloud.dialogflowcx_v3beta1.types import validation_message from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [FlowsClient, FlowsAsyncClient,]) def test_flows_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_flows_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [FlowsClient, FlowsAsyncClient,]) def test_flows_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_flows_client_get_transport_class(): def test_flows_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(FlowsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -422,7 +451,7 @@ def test_flows_client_client_options_from_dict(): def test_create_flow(transport: str = "grpc", request_type=gcdc_flow.CreateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -436,25 +465,21 @@ def test_create_flow(transport: str = "grpc", request_type=gcdc_flow.CreateFlowR name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.create_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_create_flow_from_dict(): @@ -465,7 +490,7 @@ def test_create_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -473,7 +498,6 @@ def test_create_flow_empty_call(): client.create_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() @@ -482,7 +506,7 @@ async def test_create_flow_async( transport: str = "grpc_asyncio", request_type=gcdc_flow.CreateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -497,25 +521,22 @@ async def test_create_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.create_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.CreateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -524,17 +545,17 @@ async def test_create_flow_async_from_dict(): def test_create_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = gcdc_flow.CreateFlowRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: call.return_value = gcdc_flow.Flow() - client.create_flow(request) # Establish that the underlying gRPC stub method was called. @@ -549,17 +570,17 @@ def test_create_flow_field_headers(): @pytest.mark.asyncio async def test_create_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = gcdc_flow.CreateFlowRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.create_flow(request) # Establish that the underlying gRPC stub method was called. @@ -573,13 +594,12 @@ async def test_create_flow_field_headers_async(): def test_create_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_flow( @@ -590,14 +610,12 @@ def test_create_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].flow == gcdc_flow.Flow(name="name_value") def test_create_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -611,7 +629,7 @@ def test_create_flow_flattened_error(): @pytest.mark.asyncio async def test_create_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_flow), "__call__") as call: @@ -629,15 +647,13 @@ async def test_create_flow_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].flow == gcdc_flow.Flow(name="name_value") @pytest.mark.asyncio async def test_create_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -651,7 +667,7 @@ async def test_create_flow_flattened_error_async(): def test_delete_flow(transport: str = "grpc", request_type=flow.DeleteFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -662,13 +678,11 @@ def test_delete_flow(transport: str = "grpc", request_type=flow.DeleteFlowReques with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() # Establish that the response is the type that we expect. @@ -683,7 +697,7 @@ def test_delete_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,7 +705,6 @@ def test_delete_flow_empty_call(): client.delete_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() @@ -700,7 +713,7 @@ async def test_delete_flow_async( transport: str = "grpc_asyncio", request_type=flow.DeleteFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -711,13 +724,11 @@ async def test_delete_flow_async( with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.DeleteFlowRequest() # Establish that the response is the type that we expect. @@ -730,17 +741,17 @@ async def test_delete_flow_async_from_dict(): def test_delete_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.DeleteFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: call.return_value = None - client.delete_flow(request) # Establish that the underlying gRPC stub method was called. @@ -755,17 +766,17 @@ def test_delete_flow_field_headers(): @pytest.mark.asyncio async def test_delete_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.DeleteFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_flow(request) # Establish that the underlying gRPC stub method was called. @@ -779,13 +790,12 @@ async def test_delete_flow_field_headers_async(): def test_delete_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_flow(name="name_value",) @@ -794,12 +804,11 @@ def test_delete_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -811,7 +820,7 @@ def test_delete_flow_flattened_error(): @pytest.mark.asyncio async def test_delete_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_flow), "__call__") as call: @@ -827,13 +836,12 @@ async def test_delete_flow_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -845,7 +853,7 @@ async def test_delete_flow_flattened_error_async(): def test_list_flows(transport: str = "grpc", request_type=flow.ListFlowsRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -858,19 +866,15 @@ def test_list_flows(transport: str = "grpc", request_type=flow.ListFlowsRequest) call.return_value = flow.ListFlowsResponse( next_page_token="next_page_token_value", ) - response = client.list_flows(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListFlowsPager) - assert response.next_page_token == "next_page_token_value" @@ -882,7 +886,7 @@ def test_list_flows_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 = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -890,7 +894,6 @@ def test_list_flows_empty_call(): client.list_flows() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() @@ -899,7 +902,7 @@ async def test_list_flows_async( transport: str = "grpc_asyncio", request_type=flow.ListFlowsRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -912,18 +915,15 @@ async def test_list_flows_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.ListFlowsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_flows(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.ListFlowsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListFlowsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -933,17 +933,17 @@ async def test_list_flows_async_from_dict(): def test_list_flows_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.ListFlowsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: call.return_value = flow.ListFlowsResponse() - client.list_flows(request) # Establish that the underlying gRPC stub method was called. @@ -958,11 +958,12 @@ def test_list_flows_field_headers(): @pytest.mark.asyncio async def test_list_flows_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.ListFlowsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -970,7 +971,6 @@ async def test_list_flows_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.ListFlowsResponse() ) - await client.list_flows(request) # Establish that the underlying gRPC stub method was called. @@ -984,13 +984,12 @@ async def test_list_flows_field_headers_async(): def test_list_flows_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.ListFlowsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_flows(parent="parent_value",) @@ -999,12 +998,11 @@ def test_list_flows_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_flows_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1016,7 +1014,7 @@ def test_list_flows_flattened_error(): @pytest.mark.asyncio async def test_list_flows_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1034,13 +1032,12 @@ async def test_list_flows_flattened_async(): # 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_flows_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1051,7 +1048,7 @@ async def test_list_flows_flattened_error_async(): def test_list_flows_pager(): - client = FlowsClient(credentials=credentials.AnonymousCredentials,) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1080,7 +1077,7 @@ def test_list_flows_pager(): def test_list_flows_pages(): - client = FlowsClient(credentials=credentials.AnonymousCredentials,) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_flows), "__call__") as call: @@ -1101,7 +1098,7 @@ def test_list_flows_pages(): @pytest.mark.asyncio async def test_list_flows_async_pager(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1129,7 +1126,7 @@ async def test_list_flows_async_pager(): @pytest.mark.asyncio async def test_list_flows_async_pages(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1154,7 +1151,7 @@ async def test_list_flows_async_pages(): def test_get_flow(transport: str = "grpc", request_type=flow.GetFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1168,25 +1165,21 @@ def test_get_flow(transport: str = "grpc", request_type=flow.GetFlowRequest): name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.get_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_get_flow_from_dict(): @@ -1197,7 +1190,7 @@ def test_get_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1205,7 +1198,6 @@ def test_get_flow_empty_call(): client.get_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() @@ -1214,7 +1206,7 @@ async def test_get_flow_async( transport: str = "grpc_asyncio", request_type=flow.GetFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1229,25 +1221,22 @@ async def test_get_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.get_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -1256,17 +1245,17 @@ async def test_get_flow_async_from_dict(): def test_get_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.GetFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: call.return_value = flow.Flow() - client.get_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1281,17 +1270,17 @@ def test_get_flow_field_headers(): @pytest.mark.asyncio async def test_get_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.GetFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(flow.Flow()) - await client.get_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1305,13 +1294,12 @@ async def test_get_flow_field_headers_async(): def test_get_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_flow(name="name_value",) @@ -1320,12 +1308,11 @@ def test_get_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1324,7 @@ def test_get_flow_flattened_error(): @pytest.mark.asyncio async def test_get_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_flow), "__call__") as call: @@ -1353,13 +1340,12 @@ async def test_get_flow_flattened_async(): # 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_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1371,7 +1357,7 @@ async def test_get_flow_flattened_error_async(): def test_update_flow(transport: str = "grpc", request_type=gcdc_flow.UpdateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1385,25 +1371,21 @@ def test_update_flow(transport: str = "grpc", request_type=gcdc_flow.UpdateFlowR name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) - response = client.update_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] def test_update_flow_from_dict(): @@ -1414,7 +1396,7 @@ def test_update_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1422,7 +1404,6 @@ def test_update_flow_empty_call(): client.update_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() @@ -1431,7 +1412,7 @@ async def test_update_flow_async( transport: str = "grpc_asyncio", request_type=gcdc_flow.UpdateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1446,25 +1427,22 @@ async def test_update_flow_async( name="name_value", display_name="display_name_value", description="description_value", + transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.update_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_flow.UpdateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_flow.Flow) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" + assert response.transition_route_groups == ["transition_route_groups_value"] @pytest.mark.asyncio @@ -1473,17 +1451,17 @@ async def test_update_flow_async_from_dict(): def test_update_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = gcdc_flow.UpdateFlowRequest() + request.flow.name = "flow.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: call.return_value = gcdc_flow.Flow() - client.update_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1498,17 +1476,17 @@ def test_update_flow_field_headers(): @pytest.mark.asyncio async def test_update_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = gcdc_flow.UpdateFlowRequest() + request.flow.name = "flow.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_flow.Flow()) - await client.update_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1522,32 +1500,29 @@ async def test_update_flow_field_headers_async(): def test_update_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_flow.Flow() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_flow( flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1555,13 +1530,13 @@ def test_update_flow_flattened_error(): client.update_flow( gcdc_flow.UpdateFlowRequest(), flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_flow), "__call__") as call: @@ -1573,22 +1548,20 @@ async def test_update_flow_flattened_async(): # using the keyword arguments to the method. response = await client.update_flow( flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].flow == gcdc_flow.Flow(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,13 +1569,13 @@ async def test_update_flow_flattened_error_async(): await client.update_flow( gcdc_flow.UpdateFlowRequest(), flow=gcdc_flow.Flow(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_train_flow(transport: str = "grpc", request_type=flow.TrainFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1613,13 +1586,11 @@ def test_train_flow(transport: str = "grpc", request_type=flow.TrainFlowRequest) with mock.patch.object(type(client.transport.train_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() # Establish that the response is the type that we expect. @@ -1634,7 +1605,7 @@ def test_train_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1642,7 +1613,6 @@ def test_train_flow_empty_call(): client.train_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() @@ -1651,7 +1621,7 @@ async def test_train_flow_async( transport: str = "grpc_asyncio", request_type=flow.TrainFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1664,13 +1634,11 @@ async def test_train_flow_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.TrainFlowRequest() # Establish that the response is the type that we expect. @@ -1683,17 +1651,17 @@ async def test_train_flow_async_from_dict(): def test_train_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.TrainFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1676,12 @@ def test_train_flow_field_headers(): @pytest.mark.asyncio async def test_train_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.TrainFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1689,6 @@ async def test_train_flow_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1734,13 +1702,12 @@ async def test_train_flow_field_headers_async(): def test_train_flow_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.train_flow(name="name_value",) @@ -1749,12 +1716,11 @@ def test_train_flow_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_train_flow_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1766,7 +1732,7 @@ def test_train_flow_flattened_error(): @pytest.mark.asyncio async def test_train_flow_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_flow), "__call__") as call: @@ -1784,13 +1750,12 @@ async def test_train_flow_flattened_async(): # 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_train_flow_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1802,7 +1767,7 @@ async def test_train_flow_flattened_error_async(): def test_validate_flow(transport: str = "grpc", request_type=flow.ValidateFlowRequest): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1813,19 +1778,15 @@ def test_validate_flow(transport: str = "grpc", request_type=flow.ValidateFlowRe with mock.patch.object(type(client.transport.validate_flow), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult(name="name_value",) - response = client.validate_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1837,7 +1798,7 @@ def test_validate_flow_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1845,7 +1806,6 @@ def test_validate_flow_empty_call(): client.validate_flow() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() @@ -1854,7 +1814,7 @@ async def test_validate_flow_async( transport: str = "grpc_asyncio", request_type=flow.ValidateFlowRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1867,18 +1827,15 @@ async def test_validate_flow_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult(name="name_value",) ) - response = await client.validate_flow(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.ValidateFlowRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1888,17 +1845,17 @@ async def test_validate_flow_async_from_dict(): def test_validate_flow_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.ValidateFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.validate_flow), "__call__") as call: call.return_value = flow.FlowValidationResult() - client.validate_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1913,11 +1870,12 @@ def test_validate_flow_field_headers(): @pytest.mark.asyncio async def test_validate_flow_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.ValidateFlowRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1925,7 +1883,6 @@ async def test_validate_flow_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult() ) - await client.validate_flow(request) # Establish that the underlying gRPC stub method was called. @@ -1942,7 +1899,7 @@ def test_get_flow_validation_result( transport: str = "grpc", request_type=flow.GetFlowValidationResultRequest ): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1955,19 +1912,15 @@ def test_get_flow_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult(name="name_value",) - response = client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -1979,7 +1932,7 @@ def test_get_flow_validation_result_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 = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1942,6 @@ def test_get_flow_validation_result_empty_call(): client.get_flow_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() @@ -1998,7 +1950,7 @@ async def test_get_flow_validation_result_async( transport: str = "grpc_asyncio", request_type=flow.GetFlowValidationResultRequest ): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,18 +1965,15 @@ async def test_get_flow_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult(name="name_value",) ) - response = await client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == flow.GetFlowValidationResultRequest() # Establish that the response is the type that we expect. assert isinstance(response, flow.FlowValidationResult) - assert response.name == "name_value" @@ -2034,11 +1983,12 @@ async def test_get_flow_validation_result_async_from_dict(): def test_get_flow_validation_result_field_headers(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(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 = flow.GetFlowValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1996,6 @@ def test_get_flow_validation_result_field_headers(): type(client.transport.get_flow_validation_result), "__call__" ) as call: call.return_value = flow.FlowValidationResult() - client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2061,11 +2010,12 @@ def test_get_flow_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_flow_validation_result_field_headers_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(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 = flow.GetFlowValidationResultRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2075,7 +2025,6 @@ async def test_get_flow_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( flow.FlowValidationResult() ) - await client.get_flow_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2089,7 +2038,7 @@ async def test_get_flow_validation_result_field_headers_async(): def test_get_flow_validation_result_flattened(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2097,7 +2046,6 @@ def test_get_flow_validation_result_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = flow.FlowValidationResult() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_flow_validation_result(name="name_value",) @@ -2106,12 +2054,11 @@ def test_get_flow_validation_result_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_flow_validation_result_flattened_error(): - client = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2123,7 +2070,7 @@ def test_get_flow_validation_result_flattened_error(): @pytest.mark.asyncio async def test_get_flow_validation_result_flattened_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2143,13 +2090,12 @@ async def test_get_flow_validation_result_flattened_async(): # 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_flow_validation_result_flattened_error_async(): - client = FlowsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2159,19 +2105,275 @@ async def test_get_flow_validation_result_flattened_error_async(): ) +def test_import_flow(transport: str = "grpc", request_type=flow.ImportFlowRequest): + client = FlowsClient( + 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.import_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_flow_from_dict(): + test_import_flow(request_type=dict) + + +def test_import_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + 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.import_flow), "__call__") as call: + client.import_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + +@pytest.mark.asyncio +async def test_import_flow_async( + transport: str = "grpc_asyncio", request_type=flow.ImportFlowRequest +): + client = FlowsAsyncClient( + 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.import_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ImportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_flow_async_from_dict(): + await test_import_flow_async(request_type=dict) + + +def test_import_flow_field_headers(): + client = FlowsClient(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 = flow.ImportFlowRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_flow), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_flow_field_headers_async(): + client = FlowsAsyncClient(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 = flow.ImportFlowRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_flow), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_export_flow(transport: str = "grpc", request_type=flow.ExportFlowRequest): + client = FlowsClient( + 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.export_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_flow_from_dict(): + test_export_flow(request_type=dict) + + +def test_export_flow_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = FlowsClient( + 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.export_flow), "__call__") as call: + client.export_flow() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + +@pytest.mark.asyncio +async def test_export_flow_async( + transport: str = "grpc_asyncio", request_type=flow.ExportFlowRequest +): + client = FlowsAsyncClient( + 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.export_flow), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == flow.ExportFlowRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_flow_async_from_dict(): + await test_export_flow_async(request_type=dict) + + +def test_export_flow_field_headers(): + client = FlowsClient(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 = flow.ExportFlowRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_flow), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_flow_field_headers_async(): + client = FlowsAsyncClient(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 = flow.ExportFlowRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_flow), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.export_flow(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( @@ -2181,7 +2383,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = FlowsClient( @@ -2192,7 +2394,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = FlowsClient(transport=transport) assert client.transport is transport @@ -2201,13 +2403,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.FlowsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.FlowsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2219,23 +2421,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = FlowsClient(credentials=credentials.AnonymousCredentials(),) + client = FlowsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.FlowsGrpcTransport,) def test_flows_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.FlowsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2247,7 +2449,7 @@ def test_flows_base_transport(): ) as Transport: Transport.return_value = None transport = transports.FlowsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2261,6 +2463,8 @@ def test_flows_base_transport(): "train_flow", "validate_flow", "get_flow_validation_result", + "import_flow", + "export_flow", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2272,15 +2476,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2296,19 +2525,36 @@ def test_flows_base_transport_with_credentials_file(): def test_flows_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.flows.transports.FlowsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.FlowsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2319,14 +2565,38 @@ def test_flows_auth_adc(): ) -def test_flows_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.FlowsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2336,12 +2606,123 @@ def test_flows_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_flows_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,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FlowsGrpcTransport, grpc_helpers), + (transports.FlowsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_flows_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.FlowsGrpcTransport, transports.FlowsGrpcAsyncIOTransport], ) def test_flows_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2383,7 +2764,7 @@ def test_flows_grpc_transport_client_cert_source_for_mtls(transport_class): def test_flows_host_no_port(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2393,7 +2774,7 @@ def test_flows_host_no_port(): def test_flows_host_with_port(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2442,9 +2823,9 @@ def test_flows_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2523,7 +2904,7 @@ def test_flows_transport_channel_mtls_with_adc(transport_class): def test_flows_grpc_lro_client(): client = FlowsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2536,7 +2917,7 @@ def test_flows_grpc_lro_client(): def test_flows_grpc_lro_async_client(): client = FlowsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2552,7 +2933,6 @@ def test_flow_path(): location = "clam" agent = "whelk" flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2579,7 +2959,6 @@ def test_flow_validation_result_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/validationResult".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2606,7 +2985,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2634,7 +3012,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2657,12 +3034,45 @@ def test_parse_page_path(): assert expected == actual -def test_webhook_path(): +def test_transition_route_group_path(): project = "scallop" location = "abalone" agent = "squid" - webhook = "clam" + flow = "clam" + transition_route_group = "whelk" + expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( + project=project, + location=location, + agent=agent, + flow=flow, + transition_route_group=transition_route_group, + ) + actual = FlowsClient.transition_route_group_path( + project, location, agent, flow, transition_route_group + ) + assert expected == actual + +def test_parse_transition_route_group_path(): + expected = { + "project": "octopus", + "location": "oyster", + "agent": "nudibranch", + "flow": "cuttlefish", + "transition_route_group": "mussel", + } + path = FlowsClient.transition_route_group_path(**expected) + + # Check that the path construction is reversible. + actual = FlowsClient.parse_transition_route_group_path(path) + assert expected == actual + + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2672,10 +3082,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "whelk", - "location": "octopus", - "agent": "oyster", - "webhook": "nudibranch", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = FlowsClient.webhook_path(**expected) @@ -2685,8 +3095,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "cuttlefish" - + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2696,7 +3105,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "nudibranch", } path = FlowsClient.common_billing_account_path(**expected) @@ -2706,8 +3115,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" - + folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = FlowsClient.common_folder_path(folder) assert expected == actual @@ -2715,7 +3123,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "mussel", } path = FlowsClient.common_folder_path(**expected) @@ -2725,8 +3133,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" - + organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = FlowsClient.common_organization_path(organization) assert expected == actual @@ -2734,7 +3141,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nautilus", } path = FlowsClient.common_organization_path(**expected) @@ -2744,8 +3151,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" - + project = "scallop" expected = "projects/{project}".format(project=project,) actual = FlowsClient.common_project_path(project) assert expected == actual @@ -2753,7 +3159,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "abalone", } path = FlowsClient.common_project_path(**expected) @@ -2763,9 +3169,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" - + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2775,8 +3180,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "whelk", + "location": "octopus", } path = FlowsClient.common_location_path(**expected) @@ -2790,13 +3195,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep: client = FlowsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.FlowsTransport, "_prep_wrapped_messages") as prep: transport_class = FlowsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py index 38f590c6..8e507537 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_intents.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.intents import IntentsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -82,7 +111,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -97,7 +126,7 @@ def test_intents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [IntentsClient, IntentsAsyncClient,]) def test_intents_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -140,7 +169,7 @@ def test_intents_client_get_transport_class(): def test_intents_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(IntentsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -412,7 +441,7 @@ def test_intents_client_client_options_from_dict(): def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -425,19 +454,15 @@ def test_list_intents(transport: str = "grpc", request_type=intent.ListIntentsRe call.return_value = intent.ListIntentsResponse( next_page_token="next_page_token_value", ) - response = client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListIntentsPager) - assert response.next_page_token == "next_page_token_value" @@ -449,7 +474,7 @@ def test_list_intents_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -457,7 +482,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -466,7 +490,7 @@ async def test_list_intents_async( transport: str = "grpc_asyncio", request_type=intent.ListIntentsRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -479,18 +503,15 @@ async def test_list_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_intents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListIntentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -500,17 +521,17 @@ async def test_list_intents_async_from_dict(): def test_list_intents_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: call.return_value = intent.ListIntentsResponse() - client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -525,11 +546,12 @@ def test_list_intents_field_headers(): @pytest.mark.asyncio async def test_list_intents_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.ListIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -537,7 +559,6 @@ async def test_list_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( intent.ListIntentsResponse() ) - await client.list_intents(request) # Establish that the underlying gRPC stub method was called. @@ -551,13 +572,12 @@ async def test_list_intents_field_headers_async(): def test_list_intents_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.ListIntentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_intents(parent="parent_value",) @@ -566,12 +586,11 @@ def test_list_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_intents_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -583,7 +602,7 @@ def test_list_intents_flattened_error(): @pytest.mark.asyncio async def test_list_intents_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -601,13 +620,12 @@ async def test_list_intents_flattened_async(): # 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_intents_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -618,7 +636,7 @@ async def test_list_intents_flattened_error_async(): def test_list_intents_pager(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -650,7 +668,7 @@ def test_list_intents_pager(): def test_list_intents_pages(): - client = IntentsClient(credentials=credentials.AnonymousCredentials,) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_intents), "__call__") as call: @@ -674,7 +692,7 @@ def test_list_intents_pages(): @pytest.mark.asyncio async def test_list_intents_async_pager(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -705,7 +723,7 @@ async def test_list_intents_async_pager(): @pytest.mark.asyncio async def test_list_intents_async_pages(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -733,7 +751,7 @@ async def test_list_intents_async_pages(): def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentRequest): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -750,27 +768,19 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques is_fallback=True, description="description_value", ) - response = client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -782,7 +792,7 @@ def test_get_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -790,7 +800,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -799,7 +808,7 @@ async def test_get_intent_async( transport: str = "grpc_asyncio", request_type=intent.GetIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -818,26 +827,19 @@ async def test_get_intent_async( description="description_value", ) ) - response = await client.get_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -847,17 +849,17 @@ async def test_get_intent_async_from_dict(): def test_get_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = intent.Intent() - client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +874,17 @@ def test_get_intent_field_headers(): @pytest.mark.asyncio async def test_get_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.GetIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(intent.Intent()) - await client.get_intent(request) # Establish that the underlying gRPC stub method was called. @@ -896,13 +898,12 @@ async def test_get_intent_field_headers_async(): def test_get_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_intent(name="name_value",) @@ -911,12 +912,11 @@ def test_get_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -928,7 +928,7 @@ def test_get_intent_flattened_error(): @pytest.mark.asyncio async def test_get_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_intent), "__call__") as call: @@ -944,13 +944,12 @@ async def test_get_intent_flattened_async(): # 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_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -964,7 +963,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcdc_intent.CreateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -981,27 +980,19 @@ def test_create_intent( is_fallback=True, description="description_value", ) - response = client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1013,7 +1004,7 @@ def test_create_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1021,7 +1012,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() @@ -1030,7 +1020,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcdc_intent.CreateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1049,26 +1039,19 @@ async def test_create_intent_async( description="description_value", ) ) - response = await client.create_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1078,17 +1061,17 @@ async def test_create_intent_async_from_dict(): def test_create_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = gcdc_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = gcdc_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1103,17 +1086,17 @@ def test_create_intent_field_headers(): @pytest.mark.asyncio async def test_create_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = gcdc_intent.CreateIntentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1127,13 +1110,12 @@ async def test_create_intent_field_headers_async(): def test_create_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1144,14 +1126,12 @@ def test_create_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcdc_intent.Intent(name="name_value") def test_create_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1165,7 +1145,7 @@ def test_create_intent_flattened_error(): @pytest.mark.asyncio async def test_create_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_intent), "__call__") as call: @@ -1183,15 +1163,13 @@ async def test_create_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intent == gcdc_intent.Intent(name="name_value") @pytest.mark.asyncio async def test_create_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1207,7 +1185,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcdc_intent.UpdateIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1224,27 +1202,19 @@ def test_update_intent( is_fallback=True, description="description_value", ) - response = client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1256,7 +1226,7 @@ def test_update_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1264,7 +1234,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() @@ -1273,7 +1242,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcdc_intent.UpdateIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1292,26 +1261,19 @@ async def test_update_intent_async( description="description_value", ) ) - response = await client.update_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.priority == 898 - assert response.is_fallback is True - assert response.description == "description_value" @@ -1321,17 +1283,17 @@ async def test_update_intent_async_from_dict(): def test_update_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = gcdc_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = gcdc_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1346,17 +1308,17 @@ def test_update_intent_field_headers(): @pytest.mark.asyncio async def test_update_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = gcdc_intent.UpdateIntentRequest() + request.intent.name = "intent.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1370,32 +1332,29 @@ async def test_update_intent_field_headers_async(): def test_update_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1403,13 +1362,13 @@ def test_update_intent_flattened_error(): client.update_intent( gcdc_intent.UpdateIntentRequest(), intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_intent), "__call__") as call: @@ -1421,22 +1380,20 @@ async def test_update_intent_flattened_async(): # using the keyword arguments to the method. response = await client.update_intent( intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].intent == gcdc_intent.Intent(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1444,7 +1401,7 @@ async def test_update_intent_flattened_error_async(): await client.update_intent( gcdc_intent.UpdateIntentRequest(), intent=gcdc_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1452,7 +1409,7 @@ def test_delete_intent( transport: str = "grpc", request_type=intent.DeleteIntentRequest ): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1463,13 +1420,11 @@ def test_delete_intent( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1484,7 +1439,7 @@ def test_delete_intent_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 = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1492,7 +1447,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1501,7 +1455,7 @@ async def test_delete_intent_async( transport: str = "grpc_asyncio", request_type=intent.DeleteIntentRequest ): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1512,13 +1466,11 @@ async def test_delete_intent_async( with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() # Establish that the response is the type that we expect. @@ -1531,17 +1483,17 @@ async def test_delete_intent_async_from_dict(): def test_delete_intent_field_headers(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(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 = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = None - client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1556,17 +1508,17 @@ def test_delete_intent_field_headers(): @pytest.mark.asyncio async def test_delete_intent_field_headers_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(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 = intent.DeleteIntentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1580,13 +1532,12 @@ async def test_delete_intent_field_headers_async(): def test_delete_intent_flattened(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_intent(name="name_value",) @@ -1595,12 +1546,11 @@ def test_delete_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_intent_flattened_error(): - client = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1612,7 +1562,7 @@ def test_delete_intent_flattened_error(): @pytest.mark.asyncio async def test_delete_intent_flattened_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_intent), "__call__") as call: @@ -1628,13 +1578,12 @@ async def test_delete_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_intent_flattened_error_async(): - client = IntentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1647,16 +1596,16 @@ async def test_delete_intent_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -1666,7 +1615,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = IntentsClient( @@ -1677,7 +1626,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = IntentsClient(transport=transport) assert client.transport is transport @@ -1686,13 +1635,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.IntentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.IntentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1704,23 +1653,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = IntentsClient(credentials=credentials.AnonymousCredentials(),) + client = IntentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.IntentsGrpcTransport,) def test_intents_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1732,7 +1681,7 @@ def test_intents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.IntentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1749,15 +1698,40 @@ def test_intents_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1773,19 +1747,36 @@ def test_intents_base_transport_with_credentials_file(): def test_intents_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.intents.transports.IntentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.IntentsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1796,14 +1787,38 @@ def test_intents_auth_adc(): ) -def test_intents_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.IntentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1813,12 +1828,123 @@ def test_intents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_intents_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,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.IntentsGrpcTransport, grpc_helpers), + (transports.IntentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_intents_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.IntentsGrpcTransport, transports.IntentsGrpcAsyncIOTransport], ) def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1860,7 +1986,7 @@ def test_intents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_intents_host_no_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1870,7 +1996,7 @@ def test_intents_host_no_port(): def test_intents_host_with_port(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1921,9 +2047,9 @@ def test_intents_transport_channel_mtls_with_client_cert_source(transport_class) mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2005,7 +2131,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -2032,7 +2157,6 @@ def test_intent_path(): location = "nautilus" agent = "scallop" intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2056,7 +2180,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2077,7 +2200,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2096,7 +2218,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2115,7 +2236,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2135,7 +2255,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2162,7 +2281,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.IntentsTransport, "_prep_wrapped_messages" ) as prep: client = IntentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2171,6 +2290,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = IntentsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py index cf613997..fcd7abd7 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_pages.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,25 +23,55 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.pages import PagesAsyncClient 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 ( + _API_CORE_VERSION, +) +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 from google.cloud.dialogflowcx_v3beta1.types import response_message from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +114,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [PagesClient, PagesAsyncClient,]) def test_pages_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +129,7 @@ def test_pages_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [PagesClient, PagesAsyncClient,]) def test_pages_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -143,7 +172,7 @@ def test_pages_client_get_transport_class(): def test_pages_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(PagesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -415,7 +444,7 @@ def test_pages_client_client_options_from_dict(): def test_list_pages(transport: str = "grpc", request_type=page.ListPagesRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -428,19 +457,15 @@ def test_list_pages(transport: str = "grpc", request_type=page.ListPagesRequest) call.return_value = page.ListPagesResponse( next_page_token="next_page_token_value", ) - response = client.list_pages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPagesPager) - assert response.next_page_token == "next_page_token_value" @@ -452,7 +477,7 @@ def test_list_pages_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -460,7 +485,6 @@ def test_list_pages_empty_call(): client.list_pages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() @@ -469,7 +493,7 @@ async def test_list_pages_async( transport: str = "grpc_asyncio", request_type=page.ListPagesRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,18 +506,15 @@ async def test_list_pages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( page.ListPagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_pages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.ListPagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -503,17 +524,17 @@ async def test_list_pages_async_from_dict(): def test_list_pages_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.ListPagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: call.return_value = page.ListPagesResponse() - client.list_pages(request) # Establish that the underlying gRPC stub method was called. @@ -528,11 +549,12 @@ def test_list_pages_field_headers(): @pytest.mark.asyncio async def test_list_pages_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.ListPagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -540,7 +562,6 @@ async def test_list_pages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( page.ListPagesResponse() ) - await client.list_pages(request) # Establish that the underlying gRPC stub method was called. @@ -554,13 +575,12 @@ async def test_list_pages_field_headers_async(): def test_list_pages_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = page.ListPagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_pages(parent="parent_value",) @@ -569,12 +589,11 @@ def test_list_pages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_pages_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -586,7 +605,7 @@ def test_list_pages_flattened_error(): @pytest.mark.asyncio async def test_list_pages_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -604,13 +623,12 @@ async def test_list_pages_flattened_async(): # 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_pages_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -621,7 +639,7 @@ async def test_list_pages_flattened_error_async(): def test_list_pages_pager(): - client = PagesClient(credentials=credentials.AnonymousCredentials,) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -650,7 +668,7 @@ def test_list_pages_pager(): def test_list_pages_pages(): - client = PagesClient(credentials=credentials.AnonymousCredentials,) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_pages), "__call__") as call: @@ -671,7 +689,7 @@ def test_list_pages_pages(): @pytest.mark.asyncio async def test_list_pages_async_pager(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,7 +717,7 @@ async def test_list_pages_async_pager(): @pytest.mark.asyncio async def test_list_pages_async_pages(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -724,7 +742,7 @@ async def test_list_pages_async_pages(): def test_get_page(transport: str = "grpc", request_type=page.GetPageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -739,23 +757,17 @@ def test_get_page(transport: str = "grpc", request_type=page.GetPageRequest): display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.get_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -767,7 +779,7 @@ def test_get_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -775,7 +787,6 @@ def test_get_page_empty_call(): client.get_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() @@ -784,7 +795,7 @@ async def test_get_page_async( transport: str = "grpc_asyncio", request_type=page.GetPageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -801,22 +812,17 @@ async def test_get_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.get_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.GetPageRequest() # Establish that the response is the type that we expect. assert isinstance(response, page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -826,17 +832,17 @@ async def test_get_page_async_from_dict(): def test_get_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.GetPageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: call.return_value = page.Page() - client.get_page(request) # Establish that the underlying gRPC stub method was called. @@ -851,17 +857,17 @@ def test_get_page_field_headers(): @pytest.mark.asyncio async def test_get_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.GetPageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(page.Page()) - await client.get_page(request) # Establish that the underlying gRPC stub method was called. @@ -875,13 +881,12 @@ async def test_get_page_field_headers_async(): def test_get_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_page(name="name_value",) @@ -890,12 +895,11 @@ def test_get_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -907,7 +911,7 @@ def test_get_page_flattened_error(): @pytest.mark.asyncio async def test_get_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_page), "__call__") as call: @@ -923,13 +927,12 @@ async def test_get_page_flattened_async(): # 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_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -941,7 +944,7 @@ async def test_get_page_flattened_error_async(): def test_create_page(transport: str = "grpc", request_type=gcdc_page.CreatePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -956,23 +959,17 @@ def test_create_page(transport: str = "grpc", request_type=gcdc_page.CreatePageR display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.create_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -984,7 +981,7 @@ def test_create_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -992,7 +989,6 @@ def test_create_page_empty_call(): client.create_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() @@ -1001,7 +997,7 @@ async def test_create_page_async( transport: str = "grpc_asyncio", request_type=gcdc_page.CreatePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1018,22 +1014,17 @@ async def test_create_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.create_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.CreatePageRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1043,17 +1034,17 @@ async def test_create_page_async_from_dict(): def test_create_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = gcdc_page.CreatePageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: call.return_value = gcdc_page.Page() - client.create_page(request) # Establish that the underlying gRPC stub method was called. @@ -1068,17 +1059,17 @@ def test_create_page_field_headers(): @pytest.mark.asyncio async def test_create_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = gcdc_page.CreatePageRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.create_page(request) # Establish that the underlying gRPC stub method was called. @@ -1092,13 +1083,12 @@ async def test_create_page_field_headers_async(): def test_create_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_page( @@ -1109,14 +1099,12 @@ def test_create_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].page == gcdc_page.Page(name="name_value") def test_create_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1130,7 +1118,7 @@ def test_create_page_flattened_error(): @pytest.mark.asyncio async def test_create_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_page), "__call__") as call: @@ -1148,15 +1136,13 @@ async def test_create_page_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].page == gcdc_page.Page(name="name_value") @pytest.mark.asyncio async def test_create_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1170,7 +1156,7 @@ async def test_create_page_flattened_error_async(): def test_update_page(transport: str = "grpc", request_type=gcdc_page.UpdatePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1185,23 +1171,17 @@ def test_update_page(transport: str = "grpc", request_type=gcdc_page.UpdatePageR display_name="display_name_value", transition_route_groups=["transition_route_groups_value"], ) - response = client.update_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1213,7 +1193,7 @@ def test_update_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1221,7 +1201,6 @@ def test_update_page_empty_call(): client.update_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() @@ -1230,7 +1209,7 @@ async def test_update_page_async( transport: str = "grpc_asyncio", request_type=gcdc_page.UpdatePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1247,22 +1226,17 @@ async def test_update_page_async( transition_route_groups=["transition_route_groups_value"], ) ) - response = await client.update_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_page.UpdatePageRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_page.Page) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.transition_route_groups == ["transition_route_groups_value"] @@ -1272,17 +1246,17 @@ async def test_update_page_async_from_dict(): def test_update_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = gcdc_page.UpdatePageRequest() + request.page.name = "page.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: call.return_value = gcdc_page.Page() - client.update_page(request) # Establish that the underlying gRPC stub method was called. @@ -1297,17 +1271,17 @@ def test_update_page_field_headers(): @pytest.mark.asyncio async def test_update_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = gcdc_page.UpdatePageRequest() + request.page.name = "page.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcdc_page.Page()) - await client.update_page(request) # Establish that the underlying gRPC stub method was called. @@ -1321,32 +1295,29 @@ async def test_update_page_field_headers_async(): def test_update_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_page.Page() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_page( page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1354,13 +1325,13 @@ def test_update_page_flattened_error(): client.update_page( gcdc_page.UpdatePageRequest(), page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_page), "__call__") as call: @@ -1372,22 +1343,20 @@ async def test_update_page_flattened_async(): # using the keyword arguments to the method. response = await client.update_page( page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].page == gcdc_page.Page(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1395,13 +1364,13 @@ async def test_update_page_flattened_error_async(): await client.update_page( gcdc_page.UpdatePageRequest(), page=gcdc_page.Page(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_delete_page(transport: str = "grpc", request_type=page.DeletePageRequest): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1412,13 +1381,11 @@ def test_delete_page(transport: str = "grpc", request_type=page.DeletePageReques with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() # Establish that the response is the type that we expect. @@ -1433,7 +1400,7 @@ def test_delete_page_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 = PagesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1441,7 +1408,6 @@ def test_delete_page_empty_call(): client.delete_page() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() @@ -1450,7 +1416,7 @@ async def test_delete_page_async( transport: str = "grpc_asyncio", request_type=page.DeletePageRequest ): client = PagesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1461,13 +1427,11 @@ async def test_delete_page_async( with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_page(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == page.DeletePageRequest() # Establish that the response is the type that we expect. @@ -1480,17 +1444,17 @@ async def test_delete_page_async_from_dict(): def test_delete_page_field_headers(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(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 = page.DeletePageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: call.return_value = None - client.delete_page(request) # Establish that the underlying gRPC stub method was called. @@ -1505,17 +1469,17 @@ def test_delete_page_field_headers(): @pytest.mark.asyncio async def test_delete_page_field_headers_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(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 = page.DeletePageRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_page(request) # Establish that the underlying gRPC stub method was called. @@ -1529,13 +1493,12 @@ async def test_delete_page_field_headers_async(): def test_delete_page_flattened(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_page(name="name_value",) @@ -1544,12 +1507,11 @@ def test_delete_page_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_page_flattened_error(): - client = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1561,7 +1523,7 @@ def test_delete_page_flattened_error(): @pytest.mark.asyncio async def test_delete_page_flattened_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_page), "__call__") as call: @@ -1577,13 +1539,12 @@ async def test_delete_page_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_page_flattened_error_async(): - client = PagesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = PagesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,16 +1557,16 @@ async def test_delete_page_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( @@ -1615,7 +1576,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = PagesClient( @@ -1626,7 +1587,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = PagesClient(transport=transport) assert client.transport is transport @@ -1635,13 +1596,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.PagesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.PagesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1653,23 +1614,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = PagesClient(credentials=credentials.AnonymousCredentials(),) + client = PagesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.PagesGrpcTransport,) def test_pages_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.PagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1681,7 +1642,7 @@ def test_pages_base_transport(): ) as Transport: Transport.return_value = None transport = transports.PagesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1698,15 +1659,40 @@ def test_pages_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1722,19 +1708,36 @@ def test_pages_base_transport_with_credentials_file(): def test_pages_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.pages.transports.PagesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.PagesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1745,14 +1748,38 @@ def test_pages_auth_adc(): ) -def test_pages_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.PagesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1762,12 +1789,123 @@ def test_pages_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_pages_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,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.PagesGrpcTransport, grpc_helpers), + (transports.PagesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_pages_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.PagesGrpcTransport, transports.PagesGrpcAsyncIOTransport], ) def test_pages_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1809,7 +1947,7 @@ def test_pages_grpc_transport_client_cert_source_for_mtls(transport_class): def test_pages_host_no_port(): client = PagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1819,7 +1957,7 @@ def test_pages_host_no_port(): def test_pages_host_with_port(): client = PagesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1868,9 +2006,9 @@ def test_pages_transport_channel_mtls_with_client_cert_source(transport_class): mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1952,7 +2090,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -1979,7 +2116,6 @@ def test_flow_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2006,7 +2142,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2034,7 +2169,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2063,7 +2197,6 @@ def test_transition_route_group_path(): agent = "squid" flow = "clam" transition_route_group = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -2097,7 +2230,6 @@ def test_webhook_path(): location = "nautilus" agent = "scallop" webhook = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2121,7 +2253,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2142,7 +2273,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = PagesClient.common_folder_path(folder) assert expected == actual @@ -2161,7 +2291,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = PagesClient.common_organization_path(organization) assert expected == actual @@ -2180,7 +2309,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = PagesClient.common_project_path(project) assert expected == actual @@ -2200,7 +2328,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2225,13 +2352,13 @@ def test_client_withDEFAULT_CLIENT_INFO(): with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep: client = PagesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object(transports.PagesTransport, "_prep_wrapped_messages") as prep: transport_class = PagesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py index 11ac3d07..fbcefa33 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_security_settings_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( SecuritySettingsServiceAsyncClient, @@ -42,12 +41,42 @@ from google.cloud.dialogflowcx_v3beta1.services.security_settings_service import ( transports, ) +from google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.base import ( + _API_CORE_VERSION, +) +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, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SecuritySettingsServiceClient, SecuritySettingsServiceAsyncClient,] ) def test_security_settings_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -116,7 +145,7 @@ def test_security_settings_service_client_from_service_account_info(client_class "client_class", [SecuritySettingsServiceClient, SecuritySettingsServiceAsyncClient,] ) def test_security_settings_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -173,7 +202,7 @@ def test_security_settings_service_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecuritySettingsServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -480,7 +509,7 @@ def test_create_security_settings( request_type=gcdc_security_settings.CreateSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -503,35 +532,26 @@ def test_create_security_settings( ], retention_window_days=2271, ) - response = client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -545,7 +565,7 @@ def test_create_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -555,7 +575,6 @@ def test_create_security_settings_empty_call(): client.create_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() @@ -565,7 +584,7 @@ async def test_create_security_settings_async( request_type=gcdc_security_settings.CreateSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -589,34 +608,26 @@ async def test_create_security_settings_async( ], ) ) - response = await client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.CreateSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -629,12 +640,13 @@ async def test_create_security_settings_async_from_dict(): def test_create_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -642,7 +654,6 @@ def test_create_security_settings_field_headers(): type(client.transport.create_security_settings), "__call__" ) as call: call.return_value = gcdc_security_settings.SecuritySettings() - client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -658,12 +669,13 @@ def test_create_security_settings_field_headers(): @pytest.mark.asyncio async def test_create_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.CreateSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -673,7 +685,6 @@ async def test_create_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_security_settings.SecuritySettings() ) - await client.create_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -688,7 +699,7 @@ async def test_create_security_settings_field_headers_async(): def test_create_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -697,7 +708,6 @@ def test_create_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_security_settings( @@ -711,9 +721,7 @@ def test_create_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) @@ -721,7 +729,7 @@ def test_create_security_settings_flattened(): def test_create_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -739,7 +747,7 @@ def test_create_security_settings_flattened_error(): @pytest.mark.asyncio async def test_create_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -765,9 +773,7 @@ async def test_create_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) @@ -776,7 +782,7 @@ async def test_create_security_settings_flattened_async(): @pytest.mark.asyncio async def test_create_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -795,7 +801,7 @@ def test_get_security_settings( transport: str = "grpc", request_type=security_settings.GetSecuritySettingsRequest ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -818,35 +824,26 @@ def test_get_security_settings( ], retention_window_days=2271, ) - response = client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -860,7 +857,7 @@ def test_get_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -870,7 +867,6 @@ def test_get_security_settings_empty_call(): client.get_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() @@ -880,7 +876,7 @@ async def test_get_security_settings_async( request_type=security_settings.GetSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -904,34 +900,26 @@ async def test_get_security_settings_async( ], ) ) - response = await client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.GetSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -944,12 +932,13 @@ async def test_get_security_settings_async_from_dict(): def test_get_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -957,7 +946,6 @@ def test_get_security_settings_field_headers(): type(client.transport.get_security_settings), "__call__" ) as call: call.return_value = security_settings.SecuritySettings() - client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -973,12 +961,13 @@ def test_get_security_settings_field_headers(): @pytest.mark.asyncio async def test_get_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.GetSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -988,7 +977,6 @@ async def test_get_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( security_settings.SecuritySettings() ) - await client.get_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1003,7 +991,7 @@ async def test_get_security_settings_field_headers_async(): def test_get_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1012,7 +1000,6 @@ def test_get_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_security_settings(name="name_value",) @@ -1021,13 +1008,12 @@ def test_get_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1041,7 +1027,7 @@ def test_get_security_settings_flattened_error(): @pytest.mark.asyncio async def test_get_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1062,14 +1048,13 @@ async def test_get_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1085,7 +1070,7 @@ def test_update_security_settings( request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1108,35 +1093,26 @@ def test_update_security_settings( ], retention_window_days=2271, ) - response = client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -1150,7 +1126,7 @@ def test_update_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1160,7 +1136,6 @@ def test_update_security_settings_empty_call(): client.update_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() @@ -1170,7 +1145,7 @@ async def test_update_security_settings_async( request_type=gcdc_security_settings.UpdateSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1194,34 +1169,26 @@ async def test_update_security_settings_async( ], ) ) - response = await client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_security_settings.UpdateSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_security_settings.SecuritySettings) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.redaction_strategy == gcdc_security_settings.SecuritySettings.RedactionStrategy.REDACT_WITH_SERVICE ) - assert ( response.redaction_scope == gcdc_security_settings.SecuritySettings.RedactionScope.REDACT_DISK_STORAGE ) - assert response.inspect_template == "inspect_template_value" - assert response.purge_data_types == [ gcdc_security_settings.SecuritySettings.PurgeDataType.DIALOGFLOW_HISTORY ] @@ -1234,12 +1201,13 @@ async def test_update_security_settings_async_from_dict(): def test_update_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1247,7 +1215,6 @@ def test_update_security_settings_field_headers(): type(client.transport.update_security_settings), "__call__" ) as call: call.return_value = gcdc_security_settings.SecuritySettings() - client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1266,12 +1233,13 @@ def test_update_security_settings_field_headers(): @pytest.mark.asyncio async def test_update_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_security_settings.UpdateSecuritySettingsRequest() + request.security_settings.name = "security_settings.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1281,7 +1249,6 @@ async def test_update_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_security_settings.SecuritySettings() ) - await client.update_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1299,7 +1266,7 @@ async def test_update_security_settings_field_headers_async(): def test_update_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1308,31 +1275,28 @@ def test_update_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_security_settings.SecuritySettings() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_security_settings( security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1343,14 +1307,14 @@ def test_update_security_settings_flattened_error(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1369,25 +1333,23 @@ async def test_update_security_settings_flattened_async(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].security_settings == gcdc_security_settings.SecuritySettings( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1398,7 +1360,7 @@ async def test_update_security_settings_flattened_error_async(): security_settings=gcdc_security_settings.SecuritySettings( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1406,7 +1368,7 @@ def test_list_security_settings( transport: str = "grpc", request_type=security_settings.ListSecuritySettingsRequest ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1421,19 +1383,15 @@ def test_list_security_settings( call.return_value = security_settings.ListSecuritySettingsResponse( next_page_token="next_page_token_value", ) - response = client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecuritySettingsPager) - assert response.next_page_token == "next_page_token_value" @@ -1445,7 +1403,7 @@ def test_list_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1455,7 +1413,6 @@ def test_list_security_settings_empty_call(): client.list_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() @@ -1465,7 +1422,7 @@ async def test_list_security_settings_async( request_type=security_settings.ListSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1482,18 +1439,15 @@ async def test_list_security_settings_async( next_page_token="next_page_token_value", ) ) - response = await client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.ListSecuritySettingsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSecuritySettingsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1504,12 +1458,13 @@ async def test_list_security_settings_async_from_dict(): def test_list_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1517,7 +1472,6 @@ def test_list_security_settings_field_headers(): type(client.transport.list_security_settings), "__call__" ) as call: call.return_value = security_settings.ListSecuritySettingsResponse() - client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1533,12 +1487,13 @@ def test_list_security_settings_field_headers(): @pytest.mark.asyncio async def test_list_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.ListSecuritySettingsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1548,7 +1503,6 @@ async def test_list_security_settings_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( security_settings.ListSecuritySettingsResponse() ) - await client.list_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1563,7 +1517,7 @@ async def test_list_security_settings_field_headers_async(): def test_list_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1572,7 +1526,6 @@ def test_list_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = security_settings.ListSecuritySettingsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_security_settings(parent="parent_value",) @@ -1581,13 +1534,12 @@ def test_list_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1601,7 +1553,7 @@ def test_list_security_settings_flattened_error(): @pytest.mark.asyncio async def test_list_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1622,14 +1574,13 @@ async def test_list_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1642,7 +1593,7 @@ async def test_list_security_settings_flattened_error_async(): def test_list_security_settings_pager(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1690,7 +1641,7 @@ def test_list_security_settings_pager(): def test_list_security_settings_pages(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1730,7 +1681,7 @@ def test_list_security_settings_pages(): @pytest.mark.asyncio async def test_list_security_settings_async_pager(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1777,7 +1728,7 @@ async def test_list_security_settings_async_pager(): @pytest.mark.asyncio async def test_list_security_settings_async_pages(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1823,7 +1774,7 @@ def test_delete_security_settings( request_type=security_settings.DeleteSecuritySettingsRequest, ): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1836,13 +1787,11 @@ def test_delete_security_settings( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() # Establish that the response is the type that we expect. @@ -1857,7 +1806,7 @@ def test_delete_security_settings_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 = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1867,7 +1816,6 @@ def test_delete_security_settings_empty_call(): client.delete_security_settings() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() @@ -1877,7 +1825,7 @@ async def test_delete_security_settings_async( request_type=security_settings.DeleteSecuritySettingsRequest, ): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1890,13 +1838,11 @@ async def test_delete_security_settings_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == security_settings.DeleteSecuritySettingsRequest() # Establish that the response is the type that we expect. @@ -1910,12 +1856,13 @@ async def test_delete_security_settings_async_from_dict(): def test_delete_security_settings_field_headers(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1923,7 +1870,6 @@ def test_delete_security_settings_field_headers(): type(client.transport.delete_security_settings), "__call__" ) as call: call.return_value = None - client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1939,12 +1885,13 @@ def test_delete_security_settings_field_headers(): @pytest.mark.asyncio async def test_delete_security_settings_field_headers_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = security_settings.DeleteSecuritySettingsRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1952,7 +1899,6 @@ async def test_delete_security_settings_field_headers_async(): type(client.transport.delete_security_settings), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_security_settings(request) # Establish that the underlying gRPC stub method was called. @@ -1967,7 +1913,7 @@ async def test_delete_security_settings_field_headers_async(): def test_delete_security_settings_flattened(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1976,7 +1922,6 @@ def test_delete_security_settings_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_security_settings(name="name_value",) @@ -1985,13 +1930,12 @@ def test_delete_security_settings_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_security_settings_flattened_error(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2005,7 +1949,7 @@ def test_delete_security_settings_flattened_error(): @pytest.mark.asyncio async def test_delete_security_settings_flattened_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2024,14 +1968,13 @@ async def test_delete_security_settings_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_security_settings_flattened_error_async(): client = SecuritySettingsServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -2045,16 +1988,16 @@ async def test_delete_security_settings_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( @@ -2064,7 +2007,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecuritySettingsServiceClient( @@ -2075,7 +2018,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SecuritySettingsServiceClient(transport=transport) assert client.transport is transport @@ -2084,13 +2027,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SecuritySettingsServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SecuritySettingsServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2105,8 +2048,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -2114,7 +2057,7 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance( client.transport, transports.SecuritySettingsServiceGrpcTransport, @@ -2123,9 +2066,9 @@ def test_transport_grpc_default(): def test_security_settings_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SecuritySettingsServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2137,7 +2080,7 @@ def test_security_settings_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SecuritySettingsServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2154,15 +2097,40 @@ def test_security_settings_service_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2178,19 +2146,36 @@ def test_security_settings_service_base_transport_with_credentials_file(): def test_security_settings_service_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.security_settings_service.transports.SecuritySettingsServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecuritySettingsServiceTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2201,14 +2186,44 @@ def test_security_settings_service_auth_adc(): ) -def test_security_settings_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SecuritySettingsServiceGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SecuritySettingsServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2218,6 +2233,123 @@ def test_security_settings_service_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_security_settings_service_transport_create_channel( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "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,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SecuritySettingsServiceGrpcTransport, grpc_helpers), + (transports.SecuritySettingsServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_security_settings_service_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2228,7 +2360,7 @@ def test_security_settings_service_transport_auth_adc(): def test_security_settings_service_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2270,7 +2402,7 @@ def test_security_settings_service_grpc_transport_client_cert_source_for_mtls( def test_security_settings_service_host_no_port(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2280,7 +2412,7 @@ def test_security_settings_service_host_no_port(): def test_security_settings_service_host_with_port(): client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2336,9 +2468,9 @@ def test_security_settings_service_transport_channel_mtls_with_client_cert_sourc mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2422,7 +2554,6 @@ def test_security_settings_path(): project = "squid" location = "clam" security_settings = "whelk" - expected = "projects/{project}/locations/{location}/securitySettings/{security_settings}".format( project=project, location=location, security_settings=security_settings, ) @@ -2447,7 +2578,6 @@ def test_parse_security_settings_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2468,7 +2598,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SecuritySettingsServiceClient.common_folder_path(folder) assert expected == actual @@ -2487,7 +2616,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SecuritySettingsServiceClient.common_organization_path(organization) assert expected == actual @@ -2506,7 +2634,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SecuritySettingsServiceClient.common_project_path(project) assert expected == actual @@ -2526,7 +2653,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2553,7 +2679,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SecuritySettingsServiceTransport, "_prep_wrapped_messages" ) as prep: client = SecuritySettingsServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2562,6 +2688,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SecuritySettingsServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) 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 4e0c8993..79f85a0c 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_session_entity_types.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) 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 ( + _API_CORE_VERSION, +) +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 ( session_entity_type as gcdc_session_entity_type, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -98,7 +127,7 @@ def test__get_default_mtls_endpoint(): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -115,7 +144,7 @@ def test_session_entity_types_client_from_service_account_info(client_class): "client_class", [SessionEntityTypesClient, SessionEntityTypesAsyncClient,] ) def test_session_entity_types_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -168,7 +197,7 @@ def test_session_entity_types_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SessionEntityTypesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -467,7 +496,7 @@ def test_list_session_entity_types( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -482,19 +511,15 @@ def test_list_session_entity_types( call.return_value = session_entity_type.ListSessionEntityTypesResponse( next_page_token="next_page_token_value", ) - response = client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSessionEntityTypesPager) - assert response.next_page_token == "next_page_token_value" @@ -506,7 +531,7 @@ def test_list_session_entity_types_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -516,7 +541,6 @@ def test_list_session_entity_types_empty_call(): client.list_session_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() @@ -526,7 +550,7 @@ async def test_list_session_entity_types_async( request_type=session_entity_type.ListSessionEntityTypesRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,18 +567,15 @@ async def test_list_session_entity_types_async( next_page_token="next_page_token_value", ) ) - response = await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.ListSessionEntityTypesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSessionEntityTypesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -564,11 +585,14 @@ async def test_list_session_entity_types_async_from_dict(): def test_list_session_entity_types_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -576,7 +600,6 @@ def test_list_session_entity_types_field_headers(): type(client.transport.list_session_entity_types), "__call__" ) as call: call.return_value = session_entity_type.ListSessionEntityTypesResponse() - client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -592,12 +615,13 @@ def test_list_session_entity_types_field_headers(): @pytest.mark.asyncio async def test_list_session_entity_types_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.ListSessionEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -607,7 +631,6 @@ async def test_list_session_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.ListSessionEntityTypesResponse() ) - await client.list_session_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -621,7 +644,9 @@ async def test_list_session_entity_types_field_headers_async(): def test_list_session_entity_types_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -629,7 +654,6 @@ def test_list_session_entity_types_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.ListSessionEntityTypesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_session_entity_types(parent="parent_value",) @@ -638,12 +662,13 @@ def test_list_session_entity_types_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_session_entity_types_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +681,7 @@ def test_list_session_entity_types_flattened_error(): @pytest.mark.asyncio async def test_list_session_entity_types_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -677,14 +702,13 @@ async def test_list_session_entity_types_flattened_async(): # 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_session_entity_types_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -696,7 +720,7 @@ async def test_list_session_entity_types_flattened_error_async(): def test_list_session_entity_types_pager(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -744,7 +768,7 @@ def test_list_session_entity_types_pager(): def test_list_session_entity_types_pages(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials,) + client = SessionEntityTypesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -783,7 +807,7 @@ def test_list_session_entity_types_pages(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pager(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -832,7 +856,7 @@ async def test_list_session_entity_types_async_pager(): @pytest.mark.asyncio async def test_list_session_entity_types_async_pages(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -878,7 +902,7 @@ def test_get_session_entity_type( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -894,21 +918,16 @@ def test_get_session_entity_type( name="name_value", entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -923,7 +942,7 @@ def test_get_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -933,7 +952,6 @@ def test_get_session_entity_type_empty_call(): client.get_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() @@ -943,7 +961,7 @@ async def test_get_session_entity_type_async( request_type=session_entity_type.GetSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -961,20 +979,16 @@ async def test_get_session_entity_type_async( entity_override_mode=session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.GetSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -987,11 +1001,14 @@ async def test_get_session_entity_type_async_from_dict(): def test_get_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -999,7 +1016,6 @@ def test_get_session_entity_type_field_headers(): type(client.transport.get_session_entity_type), "__call__" ) as call: call.return_value = session_entity_type.SessionEntityType() - client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1015,12 +1031,13 @@ def test_get_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_get_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.GetSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1030,7 +1047,6 @@ async def test_get_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session_entity_type.SessionEntityType() ) - await client.get_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1044,7 +1060,9 @@ async def test_get_session_entity_type_field_headers_async(): def test_get_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1052,7 +1070,6 @@ def test_get_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_session_entity_type(name="name_value",) @@ -1061,12 +1078,13 @@ def test_get_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1079,7 +1097,7 @@ def test_get_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_get_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1100,14 +1118,13 @@ async def test_get_session_entity_type_flattened_async(): # 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_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1123,7 +1140,7 @@ def test_create_session_entity_type( request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1139,21 +1156,16 @@ def test_create_session_entity_type( name="name_value", entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1168,7 +1180,7 @@ def test_create_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1178,7 +1190,6 @@ def test_create_session_entity_type_empty_call(): client.create_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcdc_session_entity_type.CreateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1206,20 +1217,16 @@ async def test_create_session_entity_type_async( entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1232,11 +1239,14 @@ async def test_create_session_entity_type_async_from_dict(): def test_create_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1244,7 +1254,6 @@ def test_create_session_entity_type_field_headers(): type(client.transport.create_session_entity_type), "__call__" ) as call: call.return_value = gcdc_session_entity_type.SessionEntityType() - client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1260,12 +1269,13 @@ def test_create_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_create_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_session_entity_type.CreateSessionEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1275,7 +1285,6 @@ async def test_create_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_session_entity_type.SessionEntityType() ) - await client.create_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1289,7 +1298,9 @@ async def test_create_session_entity_type_field_headers_async(): def test_create_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1297,7 +1308,6 @@ def test_create_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_session_entity_type( @@ -1311,9 +1321,7 @@ def test_create_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( @@ -1322,7 +1330,9 @@ def test_create_session_entity_type_flattened(): def test_create_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1349,7 @@ def test_create_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1365,9 +1375,7 @@ async def test_create_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( @@ -1378,7 +1386,7 @@ async def test_create_session_entity_type_flattened_async(): @pytest.mark.asyncio async def test_create_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1398,7 +1406,7 @@ def test_update_session_entity_type( request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1414,21 +1422,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) - response = client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1443,7 +1446,7 @@ def test_update_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1453,7 +1456,6 @@ def test_update_session_entity_type_empty_call(): client.update_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1463,7 +1465,7 @@ async def test_update_session_entity_type_async( request_type=gcdc_session_entity_type.UpdateSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1481,20 +1483,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE, ) ) - response = await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcdc_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1507,11 +1505,14 @@ async def test_update_session_entity_type_async_from_dict(): def test_update_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1519,7 +1520,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcdc_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1538,12 +1538,13 @@ def test_update_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_update_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_session_entity_type.UpdateSessionEntityTypeRequest() + request.session_entity_type.name = "session_entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1553,7 +1554,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1570,7 +1570,9 @@ async def test_update_session_entity_type_field_headers_async(): def test_update_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1578,32 +1580,31 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_session_entity_type.SessionEntityType() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_session_entity_type( session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1613,14 +1614,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1639,27 +1640,25 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].session_entity_type == gcdc_session_entity_type.SessionEntityType( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1670,7 +1669,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcdc_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1679,7 +1678,7 @@ def test_delete_session_entity_type( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1692,13 +1691,11 @@ def test_delete_session_entity_type( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1713,7 +1710,7 @@ def test_delete_session_entity_type_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 = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1723,7 +1720,6 @@ def test_delete_session_entity_type_empty_call(): client.delete_session_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() @@ -1733,7 +1729,7 @@ async def test_delete_session_entity_type_async( request_type=session_entity_type.DeleteSessionEntityTypeRequest, ): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1746,13 +1742,11 @@ async def test_delete_session_entity_type_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session_entity_type.DeleteSessionEntityTypeRequest() # Establish that the response is the type that we expect. @@ -1765,11 +1759,14 @@ async def test_delete_session_entity_type_async_from_dict(): def test_delete_session_entity_type_field_headers(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + 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 = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1777,7 +1774,6 @@ def test_delete_session_entity_type_field_headers(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = None - client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1793,12 +1789,13 @@ def test_delete_session_entity_type_field_headers(): @pytest.mark.asyncio async def test_delete_session_entity_type_field_headers_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = session_entity_type.DeleteSessionEntityTypeRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1806,7 +1803,6 @@ async def test_delete_session_entity_type_field_headers_async(): type(client.transport.delete_session_entity_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1820,7 +1816,9 @@ async def test_delete_session_entity_type_field_headers_async(): def test_delete_session_entity_type_flattened(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1828,7 +1826,6 @@ def test_delete_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_session_entity_type(name="name_value",) @@ -1837,12 +1834,13 @@ def test_delete_session_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_session_entity_type_flattened_error(): - client = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1855,7 +1853,7 @@ def test_delete_session_entity_type_flattened_error(): @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1874,14 +1872,13 @@ async def test_delete_session_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_session_entity_type_flattened_error_async(): client = SessionEntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1895,16 +1892,16 @@ async def test_delete_session_entity_type_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1914,7 +1911,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionEntityTypesClient( @@ -1925,7 +1922,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionEntityTypesClient(transport=transport) assert client.transport is transport @@ -1934,13 +1931,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionEntityTypesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionEntityTypesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1955,23 +1952,25 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = SessionEntityTypesClient(credentials=credentials.AnonymousCredentials(),) + client = SessionEntityTypesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.SessionEntityTypesGrpcTransport,) def test_session_entity_types_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1983,7 +1982,7 @@ def test_session_entity_types_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionEntityTypesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2000,15 +1999,40 @@ def test_session_entity_types_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2024,19 +2048,36 @@ def test_session_entity_types_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.session_entity_types.transports.SessionEntityTypesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionEntityTypesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2047,14 +2088,44 @@ def test_session_entity_types_auth_adc(): ) -def test_session_entity_types_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionEntityTypesGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionEntityTypesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2064,6 +2135,121 @@ def test_session_entity_types_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_session_entity_types_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,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionEntityTypesGrpcTransport, grpc_helpers), + (transports.SessionEntityTypesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_session_entity_types_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2074,7 +2260,7 @@ def test_session_entity_types_transport_auth_adc(): def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2116,7 +2302,7 @@ def test_session_entity_types_grpc_transport_client_cert_source_for_mtls( def test_session_entity_types_host_no_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2126,7 +2312,7 @@ def test_session_entity_types_host_no_port(): def test_session_entity_types_host_with_port(): client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2182,9 +2368,9 @@ def test_session_entity_types_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2270,7 +2456,6 @@ def test_session_entity_type_path(): agent = "whelk" session = "octopus" entity_type = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -2301,7 +2486,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2322,7 +2506,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2341,7 +2524,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2360,7 +2542,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2380,7 +2561,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2407,7 +2587,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionEntityTypesTransport, "_prep_wrapped_messages" ) as prep: client = SessionEntityTypesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2416,6 +2596,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionEntityTypesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py index 5cc69e9a..d944c6e7 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_sessions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,17 +23,23 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError 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 ( + _API_CORE_VERSION, +) +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 @@ -42,8 +47,32 @@ from google.cloud.dialogflowcx_v3beta1.types import session from google.cloud.dialogflowcx_v3beta1.types import session_entity_type from google.oauth2 import service_account -from google.protobuf import struct_pb2 as struct # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -87,7 +116,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -102,7 +131,7 @@ def test_sessions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [SessionsClient, SessionsAsyncClient,]) def test_sessions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -147,7 +176,7 @@ def test_sessions_client_get_transport_class(): def test_sessions_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(SessionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -423,7 +452,7 @@ def test_detect_intent( transport: str = "grpc", request_type=session.DetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -436,21 +465,16 @@ def test_detect_intent( call.return_value = session.DetectIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -462,7 +486,7 @@ def test_detect_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -470,7 +494,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() @@ -479,7 +502,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.DetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -494,20 +517,16 @@ async def test_detect_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -517,17 +536,17 @@ async def test_detect_intent_async_from_dict(): def test_detect_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: call.return_value = session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -542,11 +561,12 @@ def test_detect_intent_field_headers(): @pytest.mark.asyncio async def test_detect_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -554,7 +574,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -571,13 +590,12 @@ def test_streaming_detect_intent( transport: str = "grpc", request_type=session.StreamingDetectIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + 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() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -586,13 +604,11 @@ def test_streaming_detect_intent( ) as call: # Designate an appropriate return value for the call. call.return_value = iter([session.StreamingDetectIntentResponse()]) - response = client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -609,13 +625,12 @@ async def test_streaming_detect_intent_async( transport: str = "grpc_asyncio", request_type=session.StreamingDetectIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + 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() - requests = [request] # Mock the actual call within the gRPC stub, and fake the request. @@ -627,13 +642,11 @@ async def test_streaming_detect_intent_async( call.return_value.read = mock.AsyncMock( side_effect=[session.StreamingDetectIntentResponse()] ) - response = await client.streaming_detect_intent(iter(requests)) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert next(args[0]) == request # Establish that the response is the type that we expect. @@ -648,7 +661,7 @@ async def test_streaming_detect_intent_async_from_dict(): def test_match_intent(transport: str = "grpc", request_type=session.MatchIntentRequest): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -659,17 +672,14 @@ def test_match_intent(transport: str = "grpc", request_type=session.MatchIntentR with mock.patch.object(type(client.transport.match_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = session.MatchIntentResponse(text="text_value",) - response = client.match_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.MatchIntentResponse) @@ -681,7 +691,7 @@ def test_match_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -689,7 +699,6 @@ def test_match_intent_empty_call(): client.match_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() @@ -698,7 +707,7 @@ async def test_match_intent_async( transport: str = "grpc_asyncio", request_type=session.MatchIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -711,13 +720,11 @@ async def test_match_intent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.MatchIntentResponse() ) - response = await client.match_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.MatchIntentRequest() # Establish that the response is the type that we expect. @@ -730,17 +737,17 @@ async def test_match_intent_async_from_dict(): def test_match_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.MatchIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.match_intent), "__call__") as call: call.return_value = session.MatchIntentResponse() - client.match_intent(request) # Establish that the underlying gRPC stub method was called. @@ -755,11 +762,12 @@ def test_match_intent_field_headers(): @pytest.mark.asyncio async def test_match_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.MatchIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -767,7 +775,6 @@ async def test_match_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.MatchIntentResponse() ) - await client.match_intent(request) # Establish that the underlying gRPC stub method was called. @@ -784,7 +791,7 @@ def test_fulfill_intent( transport: str = "grpc", request_type=session.FulfillIntentRequest ): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -797,21 +804,16 @@ def test_fulfill_intent( call.return_value = session.FulfillIntentResponse( response_id="response_id_value", output_audio=b"output_audio_blob", ) - response = client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -823,7 +825,7 @@ def test_fulfill_intent_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 = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -831,7 +833,6 @@ def test_fulfill_intent_empty_call(): client.fulfill_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() @@ -840,7 +841,7 @@ async def test_fulfill_intent_async( transport: str = "grpc_asyncio", request_type=session.FulfillIntentRequest ): client = SessionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -855,20 +856,16 @@ async def test_fulfill_intent_async( response_id="response_id_value", output_audio=b"output_audio_blob", ) ) - response = await client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == session.FulfillIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, session.FulfillIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -878,17 +875,17 @@ async def test_fulfill_intent_async_from_dict(): def test_fulfill_intent_field_headers(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(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 = session.FulfillIntentRequest() + request.match_intent_request.session = "match_intent_request.session/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.fulfill_intent), "__call__") as call: call.return_value = session.FulfillIntentResponse() - client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. @@ -906,11 +903,12 @@ def test_fulfill_intent_field_headers(): @pytest.mark.asyncio async def test_fulfill_intent_field_headers_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(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 = session.FulfillIntentRequest() + request.match_intent_request.session = "match_intent_request.session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -918,7 +916,6 @@ async def test_fulfill_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( session.FulfillIntentResponse() ) - await client.fulfill_intent(request) # Establish that the underlying gRPC stub method was called. @@ -937,16 +934,16 @@ async def test_fulfill_intent_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -956,7 +953,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SessionsClient( @@ -967,7 +964,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = SessionsClient(transport=transport) assert client.transport is transport @@ -976,13 +973,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.SessionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.SessionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -994,23 +991,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.SessionsGrpcTransport,) def test_sessions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1022,7 +1019,7 @@ def test_sessions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.SessionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1038,15 +1035,40 @@ def test_sessions_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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 = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1062,19 +1084,36 @@ def test_sessions_base_transport_with_credentials_file(): def test_sessions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.sessions.transports.SessionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SessionsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1085,14 +1124,38 @@ def test_sessions_auth_adc(): ) -def test_sessions_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.SessionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1102,12 +1165,123 @@ def test_sessions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_sessions_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,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionsGrpcTransport, grpc_helpers), + (transports.SessionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_sessions_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.SessionsGrpcTransport, transports.SessionsGrpcAsyncIOTransport], ) def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1149,7 +1323,7 @@ def test_sessions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_sessions_host_no_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1159,7 +1333,7 @@ def test_sessions_host_no_port(): def test_sessions_host_with_port(): client = SessionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1210,9 +1384,9 @@ def test_sessions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1294,7 +1468,6 @@ def test_entity_type_path(): location = "clam" agent = "whelk" entity_type = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -1321,7 +1494,6 @@ def test_flow_path(): location = "nautilus" agent = "scallop" flow = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -1348,7 +1520,6 @@ def test_intent_path(): location = "nudibranch" agent = "cuttlefish" intent = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -1376,7 +1547,6 @@ def test_page_path(): agent = "whelk" flow = "octopus" page = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -1404,7 +1574,6 @@ def test_session_path(): location = "abalone" agent = "squid" session = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}".format( project=project, location=location, agent=agent, session=session, ) @@ -1432,7 +1601,6 @@ def test_session_entity_type_path(): agent = "winkle" session = "nautilus" entity_type = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format( project=project, location=location, @@ -1467,7 +1635,6 @@ def test_transition_route_group_path(): agent = "cuttlefish" flow = "mussel" transition_route_group = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -1501,7 +1668,6 @@ def test_webhook_path(): location = "octopus" agent = "oyster" webhook = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -1525,7 +1691,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1546,7 +1711,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1565,7 +1729,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1584,7 +1747,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1604,7 +1766,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1631,7 +1792,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.SessionsTransport, "_prep_wrapped_messages" ) as prep: client = SessionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1640,6 +1801,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = SessionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py index efe04685..67ea8c6b 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_test_cases.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,27 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.test_cases import TestCasesAsyncClient 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 ( + _API_CORE_VERSION, +) +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 @@ -49,11 +54,35 @@ from google.cloud.dialogflowcx_v3beta1.types import test_case as gcdc_test_case from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import any_pb2 as gp_any # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import status_pb2 as status # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [TestCasesClient, TestCasesAsyncClient,]) def test_test_cases_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -112,7 +141,7 @@ def test_test_cases_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [TestCasesClient, TestCasesAsyncClient,]) def test_test_cases_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -163,7 +192,7 @@ def test_test_cases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TestCasesClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -447,7 +476,7 @@ def test_list_test_cases( transport: str = "grpc", request_type=test_case.ListTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -460,19 +489,15 @@ def test_list_test_cases( call.return_value = test_case.ListTestCasesResponse( next_page_token="next_page_token_value", ) - response = client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCasesPager) - assert response.next_page_token == "next_page_token_value" @@ -484,7 +509,7 @@ def test_list_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -492,7 +517,6 @@ def test_list_test_cases_empty_call(): client.list_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() @@ -501,7 +525,7 @@ async def test_list_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ListTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -514,18 +538,15 @@ async def test_list_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCasesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTestCasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -535,17 +556,17 @@ async def test_list_test_cases_async_from_dict(): def test_list_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ListTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: call.return_value = test_case.ListTestCasesResponse() - client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -560,11 +581,12 @@ def test_list_test_cases_field_headers(): @pytest.mark.asyncio async def test_list_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ListTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -572,7 +594,6 @@ async def test_list_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCasesResponse() ) - await client.list_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -586,13 +607,12 @@ async def test_list_test_cases_field_headers_async(): def test_list_test_cases_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = test_case.ListTestCasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_test_cases(parent="parent_value",) @@ -601,12 +621,11 @@ def test_list_test_cases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_test_cases_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -618,7 +637,7 @@ def test_list_test_cases_flattened_error(): @pytest.mark.asyncio async def test_list_test_cases_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -636,13 +655,12 @@ async def test_list_test_cases_flattened_async(): # 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_test_cases_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -653,7 +671,7 @@ async def test_list_test_cases_flattened_error_async(): def test_list_test_cases_pager(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -691,7 +709,7 @@ def test_list_test_cases_pager(): def test_list_test_cases_pages(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_test_cases), "__call__") as call: @@ -721,7 +739,7 @@ def test_list_test_cases_pages(): @pytest.mark.asyncio async def test_list_test_cases_async_pager(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -758,7 +776,7 @@ async def test_list_test_cases_async_pager(): @pytest.mark.asyncio async def test_list_test_cases_async_pages(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -794,7 +812,7 @@ def test_batch_delete_test_cases( transport: str = "grpc", request_type=test_case.BatchDeleteTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -807,13 +825,11 @@ def test_batch_delete_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() # Establish that the response is the type that we expect. @@ -828,7 +844,7 @@ def test_batch_delete_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -838,7 +854,6 @@ def test_batch_delete_test_cases_empty_call(): client.batch_delete_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() @@ -847,7 +862,7 @@ async def test_batch_delete_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.BatchDeleteTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -860,13 +875,11 @@ async def test_batch_delete_test_cases_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchDeleteTestCasesRequest() # Establish that the response is the type that we expect. @@ -879,11 +892,12 @@ async def test_batch_delete_test_cases_async_from_dict(): def test_batch_delete_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.BatchDeleteTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -891,7 +905,6 @@ def test_batch_delete_test_cases_field_headers(): type(client.transport.batch_delete_test_cases), "__call__" ) as call: call.return_value = None - client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -906,11 +919,12 @@ def test_batch_delete_test_cases_field_headers(): @pytest.mark.asyncio async def test_batch_delete_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.BatchDeleteTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -918,7 +932,6 @@ async def test_batch_delete_test_cases_field_headers_async(): type(client.transport.batch_delete_test_cases), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.batch_delete_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -932,7 +945,7 @@ async def test_batch_delete_test_cases_field_headers_async(): def test_batch_delete_test_cases_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -940,7 +953,6 @@ def test_batch_delete_test_cases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_delete_test_cases(parent="parent_value",) @@ -949,12 +961,11 @@ def test_batch_delete_test_cases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_batch_delete_test_cases_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -966,7 +977,7 @@ def test_batch_delete_test_cases_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_test_cases_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -984,13 +995,12 @@ async def test_batch_delete_test_cases_flattened_async(): # 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_batch_delete_test_cases_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1004,7 +1014,7 @@ def test_get_test_case( transport: str = "grpc", request_type=test_case.GetTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1020,25 +1030,18 @@ def test_get_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.get_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1050,7 +1053,7 @@ def test_get_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1061,6 @@ def test_get_test_case_empty_call(): client.get_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() @@ -1067,7 +1069,7 @@ async def test_get_test_case_async( transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1085,24 +1087,18 @@ async def test_get_test_case_async( notes="notes_value", ) ) - response = await client.get_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.GetTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1112,17 +1108,17 @@ async def test_get_test_case_async_from_dict(): def test_get_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.GetTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: call.return_value = test_case.TestCase() - client.get_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1137,17 +1133,17 @@ def test_get_test_case_field_headers(): @pytest.mark.asyncio async def test_get_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.GetTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(test_case.TestCase()) - await client.get_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1161,13 +1157,12 @@ async def test_get_test_case_field_headers_async(): def test_get_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_test_case(name="name_value",) @@ -1176,12 +1171,11 @@ def test_get_test_case_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1193,7 +1187,7 @@ def test_get_test_case_flattened_error(): @pytest.mark.asyncio async def test_get_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_test_case), "__call__") as call: @@ -1209,13 +1203,12 @@ async def test_get_test_case_flattened_async(): # 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_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1229,7 +1222,7 @@ def test_create_test_case( transport: str = "grpc", request_type=gcdc_test_case.CreateTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1245,25 +1238,18 @@ def test_create_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.create_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1275,7 +1261,7 @@ def test_create_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1269,6 @@ def test_create_test_case_empty_call(): client.create_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() @@ -1292,7 +1277,7 @@ async def test_create_test_case_async( transport: str = "grpc_asyncio", request_type=gcdc_test_case.CreateTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1310,24 +1295,18 @@ async def test_create_test_case_async( notes="notes_value", ) ) - response = await client.create_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.CreateTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1337,17 +1316,17 @@ async def test_create_test_case_async_from_dict(): def test_create_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = gcdc_test_case.CreateTestCaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: call.return_value = gcdc_test_case.TestCase() - client.create_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1362,11 +1341,12 @@ def test_create_test_case_field_headers(): @pytest.mark.asyncio async def test_create_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = gcdc_test_case.CreateTestCaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1374,7 +1354,6 @@ async def test_create_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_test_case.TestCase() ) - await client.create_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1388,13 +1367,12 @@ async def test_create_test_case_field_headers_async(): def test_create_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_test_case( @@ -1405,14 +1383,12 @@ def test_create_test_case_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") def test_create_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1426,7 +1402,7 @@ def test_create_test_case_flattened_error(): @pytest.mark.asyncio async def test_create_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_test_case), "__call__") as call: @@ -1446,15 +1422,13 @@ async def test_create_test_case_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") @pytest.mark.asyncio async def test_create_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1470,7 +1444,7 @@ def test_update_test_case( transport: str = "grpc", request_type=gcdc_test_case.UpdateTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1486,25 +1460,18 @@ def test_update_test_case( display_name="display_name_value", notes="notes_value", ) - response = client.update_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1516,7 +1483,7 @@ def test_update_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1524,7 +1491,6 @@ def test_update_test_case_empty_call(): client.update_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() @@ -1533,7 +1499,7 @@ async def test_update_test_case_async( transport: str = "grpc_asyncio", request_type=gcdc_test_case.UpdateTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1551,24 +1517,18 @@ async def test_update_test_case_async( notes="notes_value", ) ) - response = await client.update_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_test_case.UpdateTestCaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_test_case.TestCase) - assert response.name == "name_value" - assert response.tags == ["tags_value"] - assert response.display_name == "display_name_value" - assert response.notes == "notes_value" @@ -1578,17 +1538,17 @@ async def test_update_test_case_async_from_dict(): def test_update_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = gcdc_test_case.UpdateTestCaseRequest() + request.test_case.name = "test_case.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: call.return_value = gcdc_test_case.TestCase() - client.update_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1605,11 +1565,12 @@ def test_update_test_case_field_headers(): @pytest.mark.asyncio async def test_update_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = gcdc_test_case.UpdateTestCaseRequest() + request.test_case.name = "test_case.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1617,7 +1578,6 @@ async def test_update_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_test_case.TestCase() ) - await client.update_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1633,32 +1593,29 @@ async def test_update_test_case_field_headers_async(): def test_update_test_case_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_test_case.TestCase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_test_case( test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_test_case_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1666,13 +1623,13 @@ def test_update_test_case_flattened_error(): client.update_test_case( gcdc_test_case.UpdateTestCaseRequest(), test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_test_case_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_test_case), "__call__") as call: @@ -1686,22 +1643,20 @@ async def test_update_test_case_flattened_async(): # using the keyword arguments to the method. response = await client.update_test_case( test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].test_case == gcdc_test_case.TestCase(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_test_case_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1709,7 +1664,7 @@ async def test_update_test_case_flattened_error_async(): await client.update_test_case( gcdc_test_case.UpdateTestCaseRequest(), test_case=gcdc_test_case.TestCase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1717,7 +1672,7 @@ def test_run_test_case( transport: str = "grpc", request_type=test_case.RunTestCaseRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1728,13 +1683,11 @@ def test_run_test_case( with mock.patch.object(type(client.transport.run_test_case), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.run_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() # Establish that the response is the type that we expect. @@ -1749,7 +1702,7 @@ def test_run_test_case_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1757,7 +1710,6 @@ def test_run_test_case_empty_call(): client.run_test_case() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() @@ -1766,7 +1718,7 @@ async def test_run_test_case_async( transport: str = "grpc_asyncio", request_type=test_case.RunTestCaseRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1779,13 +1731,11 @@ async def test_run_test_case_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.run_test_case(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.RunTestCaseRequest() # Establish that the response is the type that we expect. @@ -1798,17 +1748,17 @@ async def test_run_test_case_async_from_dict(): def test_run_test_case_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.RunTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.run_test_case), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.run_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1823,11 +1773,12 @@ def test_run_test_case_field_headers(): @pytest.mark.asyncio async def test_run_test_case_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.RunTestCaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1835,7 +1786,6 @@ async def test_run_test_case_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.run_test_case(request) # Establish that the underlying gRPC stub method was called. @@ -1852,7 +1802,7 @@ def test_batch_run_test_cases( transport: str = "grpc", request_type=test_case.BatchRunTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1865,13 +1815,11 @@ def test_batch_run_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() # Establish that the response is the type that we expect. @@ -1886,7 +1834,7 @@ def test_batch_run_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1896,7 +1844,6 @@ def test_batch_run_test_cases_empty_call(): client.batch_run_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() @@ -1905,7 +1852,7 @@ async def test_batch_run_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.BatchRunTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1920,13 +1867,11 @@ async def test_batch_run_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.BatchRunTestCasesRequest() # Establish that the response is the type that we expect. @@ -1939,11 +1884,12 @@ async def test_batch_run_test_cases_async_from_dict(): def test_batch_run_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.BatchRunTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1951,7 +1897,6 @@ def test_batch_run_test_cases_field_headers(): type(client.transport.batch_run_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -1966,11 +1911,12 @@ def test_batch_run_test_cases_field_headers(): @pytest.mark.asyncio async def test_batch_run_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.BatchRunTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1980,7 +1926,6 @@ async def test_batch_run_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_run_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -1997,7 +1942,7 @@ def test_calculate_coverage( transport: str = "grpc", request_type=test_case.CalculateCoverageRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2015,19 +1960,15 @@ def test_calculate_coverage( intents=[test_case.IntentCoverage.Intent(intent="intent_value")] ), ) - response = client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() # Establish that the response is the type that we expect. - assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == "agent_value" @@ -2039,7 +1980,7 @@ def test_calculate_coverage_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2049,7 +1990,6 @@ def test_calculate_coverage_empty_call(): client.calculate_coverage() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() @@ -2058,7 +1998,7 @@ async def test_calculate_coverage_async( transport: str = "grpc_asyncio", request_type=test_case.CalculateCoverageRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2073,18 +2013,15 @@ async def test_calculate_coverage_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.CalculateCoverageResponse(agent="agent_value",) ) - response = await client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.CalculateCoverageRequest() # Establish that the response is the type that we expect. assert isinstance(response, test_case.CalculateCoverageResponse) - assert response.agent == "agent_value" @@ -2094,11 +2031,12 @@ async def test_calculate_coverage_async_from_dict(): def test_calculate_coverage_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.CalculateCoverageRequest() + request.agent = "agent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2106,7 +2044,6 @@ def test_calculate_coverage_field_headers(): type(client.transport.calculate_coverage), "__call__" ) as call: call.return_value = test_case.CalculateCoverageResponse() - client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. @@ -2121,11 +2058,12 @@ def test_calculate_coverage_field_headers(): @pytest.mark.asyncio async def test_calculate_coverage_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.CalculateCoverageRequest() + request.agent = "agent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2135,7 +2073,6 @@ async def test_calculate_coverage_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.CalculateCoverageResponse() ) - await client.calculate_coverage(request) # Establish that the underlying gRPC stub method was called. @@ -2152,7 +2089,7 @@ def test_import_test_cases( transport: str = "grpc", request_type=test_case.ImportTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2165,13 +2102,11 @@ def test_import_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2186,7 +2121,7 @@ def test_import_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2196,7 +2131,6 @@ def test_import_test_cases_empty_call(): client.import_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() @@ -2205,7 +2139,7 @@ async def test_import_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ImportTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2220,13 +2154,11 @@ async def test_import_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ImportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2239,11 +2171,12 @@ async def test_import_test_cases_async_from_dict(): def test_import_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ImportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2251,7 +2184,6 @@ def test_import_test_cases_field_headers(): type(client.transport.import_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2266,11 +2198,12 @@ def test_import_test_cases_field_headers(): @pytest.mark.asyncio async def test_import_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ImportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2280,7 +2213,6 @@ async def test_import_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2297,7 +2229,7 @@ def test_export_test_cases( transport: str = "grpc", request_type=test_case.ExportTestCasesRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2310,13 +2242,11 @@ def test_export_test_cases( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2331,7 +2261,7 @@ def test_export_test_cases_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2341,7 +2271,6 @@ def test_export_test_cases_empty_call(): client.export_test_cases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() @@ -2350,7 +2279,7 @@ async def test_export_test_cases_async( transport: str = "grpc_asyncio", request_type=test_case.ExportTestCasesRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2365,13 +2294,11 @@ async def test_export_test_cases_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ExportTestCasesRequest() # Establish that the response is the type that we expect. @@ -2384,11 +2311,12 @@ async def test_export_test_cases_async_from_dict(): def test_export_test_cases_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ExportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2396,7 +2324,6 @@ def test_export_test_cases_field_headers(): type(client.transport.export_test_cases), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2411,11 +2338,12 @@ def test_export_test_cases_field_headers(): @pytest.mark.asyncio async def test_export_test_cases_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ExportTestCasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2425,7 +2353,6 @@ async def test_export_test_cases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_test_cases(request) # Establish that the underlying gRPC stub method was called. @@ -2442,7 +2369,7 @@ def test_list_test_case_results( transport: str = "grpc", request_type=test_case.ListTestCaseResultsRequest ): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2457,19 +2384,15 @@ def test_list_test_case_results( call.return_value = test_case.ListTestCaseResultsResponse( next_page_token="next_page_token_value", ) - response = client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTestCaseResultsPager) - assert response.next_page_token == "next_page_token_value" @@ -2481,7 +2404,7 @@ def test_list_test_case_results_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 = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2491,7 +2414,6 @@ def test_list_test_case_results_empty_call(): client.list_test_case_results() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() @@ -2500,7 +2422,7 @@ async def test_list_test_case_results_async( transport: str = "grpc_asyncio", request_type=test_case.ListTestCaseResultsRequest ): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2517,18 +2439,15 @@ async def test_list_test_case_results_async( next_page_token="next_page_token_value", ) ) - response = await client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == test_case.ListTestCaseResultsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTestCaseResultsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2538,11 +2457,12 @@ async def test_list_test_case_results_async_from_dict(): def test_list_test_case_results_field_headers(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(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 = test_case.ListTestCaseResultsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2550,7 +2470,6 @@ def test_list_test_case_results_field_headers(): type(client.transport.list_test_case_results), "__call__" ) as call: call.return_value = test_case.ListTestCaseResultsResponse() - client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. @@ -2565,11 +2484,12 @@ def test_list_test_case_results_field_headers(): @pytest.mark.asyncio async def test_list_test_case_results_field_headers_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(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 = test_case.ListTestCaseResultsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2579,7 +2499,6 @@ async def test_list_test_case_results_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( test_case.ListTestCaseResultsResponse() ) - await client.list_test_case_results(request) # Establish that the underlying gRPC stub method was called. @@ -2593,7 +2512,7 @@ async def test_list_test_case_results_field_headers_async(): def test_list_test_case_results_flattened(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2601,7 +2520,6 @@ def test_list_test_case_results_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = test_case.ListTestCaseResultsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_test_case_results(parent="parent_value",) @@ -2610,12 +2528,11 @@ def test_list_test_case_results_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_test_case_results_flattened_error(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2627,7 +2544,7 @@ def test_list_test_case_results_flattened_error(): @pytest.mark.asyncio async def test_list_test_case_results_flattened_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2647,13 +2564,12 @@ async def test_list_test_case_results_flattened_async(): # 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_test_case_results_flattened_error_async(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2664,7 +2580,7 @@ async def test_list_test_case_results_flattened_error_async(): def test_list_test_case_results_pager(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2709,7 +2625,7 @@ def test_list_test_case_results_pager(): def test_list_test_case_results_pages(): - client = TestCasesClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2746,7 +2662,7 @@ def test_list_test_case_results_pages(): @pytest.mark.asyncio async def test_list_test_case_results_async_pager(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2790,7 +2706,7 @@ async def test_list_test_case_results_async_pager(): @pytest.mark.asyncio async def test_list_test_case_results_async_pages(): - client = TestCasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2829,19 +2745,241 @@ async def test_list_test_case_results_async_pages(): assert page_.raw_page.next_page_token == token +def test_get_test_case_result( + transport: str = "grpc", request_type=test_case.GetTestCaseResultRequest +): + client = TestCasesClient( + 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_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult( + name="name_value", + environment="environment_value", + test_result=test_case.TestResult.PASSED, + ) + response = client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == "name_value" + assert response.environment == "environment_value" + assert response.test_result == test_case.TestResult.PASSED + + +def test_get_test_case_result_from_dict(): + test_get_test_case_result(request_type=dict) + + +def test_get_test_case_result_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 = TestCasesClient( + 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_test_case_result), "__call__" + ) as call: + client.get_test_case_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + +@pytest.mark.asyncio +async def test_get_test_case_result_async( + transport: str = "grpc_asyncio", request_type=test_case.GetTestCaseResultRequest +): + client = TestCasesAsyncClient( + 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_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult( + name="name_value", + environment="environment_value", + test_result=test_case.TestResult.PASSED, + ) + ) + response = await client.get_test_case_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == test_case.GetTestCaseResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, test_case.TestCaseResult) + assert response.name == "name_value" + assert response.environment == "environment_value" + assert response.test_result == test_case.TestResult.PASSED + + +@pytest.mark.asyncio +async def test_get_test_case_result_async_from_dict(): + await test_get_test_case_result_async(request_type=dict) + + +def test_get_test_case_result_field_headers(): + client = TestCasesClient(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 = test_case.GetTestCaseResultRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + call.return_value = test_case.TestCaseResult() + client.get_test_case_result(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_test_case_result_field_headers_async(): + client = TestCasesAsyncClient(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 = test_case.GetTestCaseResultRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult() + ) + await client.get_test_case_result(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_test_case_result_flattened(): + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_test_case_result(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_test_case_result_flattened_error(): + client = TestCasesClient(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_test_case_result( + test_case.GetTestCaseResultRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_test_case_result_flattened_async(): + client = TestCasesAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_test_case_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = test_case.TestCaseResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + test_case.TestCaseResult() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_test_case_result(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_test_case_result_flattened_error_async(): + client = TestCasesAsyncClient(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_test_case_result( + test_case.GetTestCaseResultRequest(), name="name_value", + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( @@ -2851,7 +2989,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TestCasesClient( @@ -2862,7 +3000,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TestCasesClient(transport=transport) assert client.transport is transport @@ -2871,13 +3009,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TestCasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TestCasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2889,23 +3027,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = TestCasesClient(credentials=credentials.AnonymousCredentials(),) + client = TestCasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.TestCasesGrpcTransport,) def test_test_cases_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TestCasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2917,7 +3055,7 @@ def test_test_cases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TestCasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2934,6 +3072,7 @@ def test_test_cases_base_transport(): "import_test_cases", "export_test_cases", "list_test_case_results", + "get_test_case_result", ) for method in methods: with pytest.raises(NotImplementedError): @@ -2945,15 +3084,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2969,19 +3133,36 @@ def test_test_cases_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.test_cases.transports.TestCasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TestCasesTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2992,14 +3173,38 @@ def test_test_cases_auth_adc(): ) -def test_test_cases_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TestCasesGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -3009,12 +3214,125 @@ def test_test_cases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_test_cases_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,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TestCasesGrpcTransport, grpc_helpers), + (transports.TestCasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_test_cases_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.TestCasesGrpcTransport, transports.TestCasesGrpcAsyncIOTransport], ) def test_test_cases_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3056,7 +3374,7 @@ def test_test_cases_grpc_transport_client_cert_source_for_mtls(transport_class): def test_test_cases_host_no_port(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3066,7 +3384,7 @@ def test_test_cases_host_no_port(): def test_test_cases_host_with_port(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3117,9 +3435,9 @@ def test_test_cases_transport_channel_mtls_with_client_cert_source(transport_cla mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3198,7 +3516,7 @@ def test_test_cases_transport_channel_mtls_with_adc(transport_class): def test_test_cases_grpc_lro_client(): client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3211,7 +3529,7 @@ def test_test_cases_grpc_lro_client(): def test_test_cases_grpc_lro_async_client(): client = TestCasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3226,7 +3544,6 @@ def test_agent_path(): project = "squid" location = "clam" agent = "whelk" - expected = "projects/{project}/locations/{location}/agents/{agent}".format( project=project, location=location, agent=agent, ) @@ -3252,7 +3569,6 @@ def test_entity_type_path(): location = "mussel" agent = "winkle" entity_type = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/entityTypes/{entity_type}".format( project=project, location=location, agent=agent, entity_type=entity_type, ) @@ -3279,7 +3595,6 @@ def test_environment_path(): location = "octopus" agent = "oyster" environment = "nudibranch" - expected = "projects/{project}/locations/{location}/agents/{agent}/environments/{environment}".format( project=project, location=location, agent=agent, environment=environment, ) @@ -3306,7 +3621,6 @@ def test_flow_path(): location = "abalone" agent = "squid" flow = "clam" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -3333,7 +3647,6 @@ def test_intent_path(): location = "mussel" agent = "winkle" intent = "nautilus" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -3361,7 +3674,6 @@ def test_page_path(): agent = "oyster" flow = "nudibranch" page = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -3389,7 +3701,6 @@ def test_test_case_path(): location = "clam" agent = "whelk" test_case = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}".format( project=project, location=location, agent=agent, test_case=test_case, ) @@ -3417,7 +3728,6 @@ def test_test_case_result_path(): agent = "scallop" test_case = "abalone" result = "squid" - expected = "projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}".format( project=project, location=location, @@ -3452,7 +3762,6 @@ def test_transition_route_group_path(): agent = "winkle" flow = "nautilus" transition_route_group = "scallop" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -3486,7 +3795,6 @@ def test_webhook_path(): location = "nudibranch" agent = "cuttlefish" webhook = "mussel" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -3510,7 +3818,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3531,7 +3838,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = TestCasesClient.common_folder_path(folder) assert expected == actual @@ -3550,7 +3856,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = TestCasesClient.common_organization_path(organization) assert expected == actual @@ -3569,7 +3874,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = TestCasesClient.common_project_path(project) assert expected == actual @@ -3589,7 +3893,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3616,7 +3919,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TestCasesTransport, "_prep_wrapped_messages" ) as prep: client = TestCasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3625,6 +3928,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TestCasesClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) 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 36bc1431..718f6680 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_transition_route_groups.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,13 +23,13 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import ( TransitionRouteGroupsAsyncClient, @@ -42,6 +41,12 @@ from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups import ( transports, ) +from google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.base import ( + _API_CORE_VERSION, +) +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 @@ -50,8 +55,32 @@ transition_route_group as gcdc_transition_route_group, ) from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -103,7 +132,7 @@ def test__get_default_mtls_endpoint(): "client_class", [TransitionRouteGroupsClient, TransitionRouteGroupsAsyncClient,] ) def test_transition_route_groups_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -120,7 +149,7 @@ def test_transition_route_groups_client_from_service_account_info(client_class): "client_class", [TransitionRouteGroupsClient, TransitionRouteGroupsAsyncClient,] ) def test_transition_route_groups_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -177,7 +206,7 @@ def test_transition_route_groups_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(TransitionRouteGroupsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -484,7 +513,7 @@ def test_list_transition_route_groups( request_type=transition_route_group.ListTransitionRouteGroupsRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -499,19 +528,15 @@ def test_list_transition_route_groups( call.return_value = transition_route_group.ListTransitionRouteGroupsResponse( next_page_token="next_page_token_value", ) - response = client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTransitionRouteGroupsPager) - assert response.next_page_token == "next_page_token_value" @@ -523,7 +548,7 @@ def test_list_transition_route_groups_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -533,7 +558,6 @@ def test_list_transition_route_groups_empty_call(): client.list_transition_route_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() @@ -543,7 +567,7 @@ async def test_list_transition_route_groups_async( request_type=transition_route_group.ListTransitionRouteGroupsRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -560,18 +584,15 @@ async def test_list_transition_route_groups_async( next_page_token="next_page_token_value", ) ) - response = await client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.ListTransitionRouteGroupsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListTransitionRouteGroupsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -582,12 +603,13 @@ async def test_list_transition_route_groups_async_from_dict(): def test_list_transition_route_groups_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.ListTransitionRouteGroupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -595,7 +617,6 @@ def test_list_transition_route_groups_field_headers(): type(client.transport.list_transition_route_groups), "__call__" ) as call: call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. @@ -611,12 +632,13 @@ def test_list_transition_route_groups_field_headers(): @pytest.mark.asyncio async def test_list_transition_route_groups_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.ListTransitionRouteGroupsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -626,7 +648,6 @@ async def test_list_transition_route_groups_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transition_route_group.ListTransitionRouteGroupsResponse() ) - await client.list_transition_route_groups(request) # Establish that the underlying gRPC stub method was called. @@ -641,7 +662,7 @@ async def test_list_transition_route_groups_field_headers_async(): def test_list_transition_route_groups_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -650,7 +671,6 @@ def test_list_transition_route_groups_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = transition_route_group.ListTransitionRouteGroupsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_transition_route_groups(parent="parent_value",) @@ -659,13 +679,12 @@ def test_list_transition_route_groups_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_transition_route_groups_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -680,7 +699,7 @@ def test_list_transition_route_groups_flattened_error(): @pytest.mark.asyncio async def test_list_transition_route_groups_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -701,14 +720,13 @@ async def test_list_transition_route_groups_flattened_async(): # 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_transition_route_groups_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -721,7 +739,9 @@ async def test_list_transition_route_groups_flattened_error_async(): def test_list_transition_route_groups_pager(): - client = TransitionRouteGroupsClient(credentials=credentials.AnonymousCredentials,) + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -771,7 +791,9 @@ def test_list_transition_route_groups_pager(): def test_list_transition_route_groups_pages(): - client = TransitionRouteGroupsClient(credentials=credentials.AnonymousCredentials,) + client = TransitionRouteGroupsClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -812,7 +834,7 @@ def test_list_transition_route_groups_pages(): @pytest.mark.asyncio async def test_list_transition_route_groups_async_pager(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -864,7 +886,7 @@ async def test_list_transition_route_groups_async_pager(): @pytest.mark.asyncio async def test_list_transition_route_groups_async_pages(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -914,7 +936,7 @@ def test_get_transition_route_group( request_type=transition_route_group.GetTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -929,21 +951,16 @@ def test_get_transition_route_group( call.return_value = transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -955,7 +972,7 @@ def test_get_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -965,7 +982,6 @@ def test_get_transition_route_group_empty_call(): client.get_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() @@ -975,7 +991,7 @@ async def test_get_transition_route_group_async( request_type=transition_route_group.GetTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -992,20 +1008,16 @@ async def test_get_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.GetTransitionRouteGroupRequest() # Establish that the response is the type that we expect. assert isinstance(response, transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1016,12 +1028,13 @@ async def test_get_transition_route_group_async_from_dict(): def test_get_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.GetTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1029,7 +1042,6 @@ def test_get_transition_route_group_field_headers(): type(client.transport.get_transition_route_group), "__call__" ) as call: call.return_value = transition_route_group.TransitionRouteGroup() - client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1045,12 +1057,13 @@ def test_get_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_get_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.GetTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1060,7 +1073,6 @@ async def test_get_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( transition_route_group.TransitionRouteGroup() ) - await client.get_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1075,7 +1087,7 @@ async def test_get_transition_route_group_field_headers_async(): def test_get_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1084,7 +1096,6 @@ def test_get_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_transition_route_group(name="name_value",) @@ -1093,13 +1104,12 @@ def test_get_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1113,7 +1123,7 @@ def test_get_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_get_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1134,14 +1144,13 @@ async def test_get_transition_route_group_flattened_async(): # 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_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1157,7 +1166,7 @@ def test_create_transition_route_group( request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1172,23 +1181,18 @@ def test_create_transition_route_group( call.return_value = gcdc_transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1200,7 +1204,7 @@ def test_create_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1210,7 +1214,6 @@ def test_create_transition_route_group_empty_call(): client.create_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) @@ -1222,7 +1225,7 @@ async def test_create_transition_route_group_async( request_type=gcdc_transition_route_group.CreateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1239,22 +1242,18 @@ async def test_create_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.CreateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1265,12 +1264,13 @@ async def test_create_transition_route_group_async_from_dict(): def test_create_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1278,7 +1278,6 @@ def test_create_transition_route_group_field_headers(): type(client.transport.create_transition_route_group), "__call__" ) as call: call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1294,12 +1293,13 @@ def test_create_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_create_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.CreateTransitionRouteGroupRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1309,7 +1309,6 @@ async def test_create_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_transition_route_group.TransitionRouteGroup() ) - await client.create_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1324,7 +1323,7 @@ async def test_create_transition_route_group_field_headers_async(): def test_create_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1333,7 +1332,6 @@ def test_create_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_transition_route_group( @@ -1347,9 +1345,7 @@ def test_create_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( @@ -1359,7 +1355,7 @@ def test_create_transition_route_group_flattened(): def test_create_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1377,7 +1373,7 @@ def test_create_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_create_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1403,9 +1399,7 @@ async def test_create_transition_route_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( @@ -1416,7 +1410,7 @@ async def test_create_transition_route_group_flattened_async(): @pytest.mark.asyncio async def test_create_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1436,7 +1430,7 @@ def test_update_transition_route_group( request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1451,23 +1445,18 @@ def test_update_transition_route_group( call.return_value = gcdc_transition_route_group.TransitionRouteGroup( name="name_value", display_name="display_name_value", ) - response = client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1479,7 +1468,7 @@ def test_update_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1489,7 +1478,6 @@ def test_update_transition_route_group_empty_call(): client.update_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) @@ -1501,7 +1489,7 @@ async def test_update_transition_route_group_async( request_type=gcdc_transition_route_group.UpdateTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1518,22 +1506,18 @@ async def test_update_transition_route_group_async( name="name_value", display_name="display_name_value", ) ) - response = await client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert ( args[0] == gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() ) # Establish that the response is the type that we expect. assert isinstance(response, gcdc_transition_route_group.TransitionRouteGroup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" @@ -1544,12 +1528,13 @@ async def test_update_transition_route_group_async_from_dict(): def test_update_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + request.transition_route_group.name = "transition_route_group.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1557,7 +1542,6 @@ def test_update_transition_route_group_field_headers(): type(client.transport.update_transition_route_group), "__call__" ) as call: call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1576,12 +1560,13 @@ def test_update_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_update_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = gcdc_transition_route_group.UpdateTransitionRouteGroupRequest() + request.transition_route_group.name = "transition_route_group.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1591,7 +1576,6 @@ async def test_update_transition_route_group_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_transition_route_group.TransitionRouteGroup() ) - await client.update_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1609,7 +1593,7 @@ async def test_update_transition_route_group_field_headers_async(): def test_update_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1618,33 +1602,30 @@ def test_update_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcdc_transition_route_group.TransitionRouteGroup() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_transition_route_group( transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1655,14 +1636,14 @@ def test_update_transition_route_group_flattened_error(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1681,27 +1662,25 @@ async def test_update_transition_route_group_flattened_async(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[ 0 ].transition_route_group == gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ) - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1712,7 +1691,7 @@ async def test_update_transition_route_group_flattened_error_async(): transition_route_group=gcdc_transition_route_group.TransitionRouteGroup( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1721,7 +1700,7 @@ def test_delete_transition_route_group( request_type=transition_route_group.DeleteTransitionRouteGroupRequest, ): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1734,13 +1713,11 @@ def test_delete_transition_route_group( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() # Establish that the response is the type that we expect. @@ -1755,7 +1732,7 @@ def test_delete_transition_route_group_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 = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1765,7 +1742,6 @@ def test_delete_transition_route_group_empty_call(): client.delete_transition_route_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() @@ -1775,7 +1751,7 @@ async def test_delete_transition_route_group_async( request_type=transition_route_group.DeleteTransitionRouteGroupRequest, ): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1788,13 +1764,11 @@ async def test_delete_transition_route_group_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == transition_route_group.DeleteTransitionRouteGroupRequest() # Establish that the response is the type that we expect. @@ -1808,12 +1782,13 @@ async def test_delete_transition_route_group_async_from_dict(): def test_delete_transition_route_group_field_headers(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.DeleteTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1821,7 +1796,6 @@ def test_delete_transition_route_group_field_headers(): type(client.transport.delete_transition_route_group), "__call__" ) as call: call.return_value = None - client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1837,12 +1811,13 @@ def test_delete_transition_route_group_field_headers(): @pytest.mark.asyncio async def test_delete_transition_route_group_field_headers_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + 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 = transition_route_group.DeleteTransitionRouteGroupRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1850,7 +1825,6 @@ async def test_delete_transition_route_group_field_headers_async(): type(client.transport.delete_transition_route_group), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_transition_route_group(request) # Establish that the underlying gRPC stub method was called. @@ -1865,7 +1839,7 @@ async def test_delete_transition_route_group_field_headers_async(): def test_delete_transition_route_group_flattened(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1874,7 +1848,6 @@ def test_delete_transition_route_group_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_transition_route_group(name="name_value",) @@ -1883,13 +1856,12 @@ def test_delete_transition_route_group_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_transition_route_group_flattened_error(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1904,7 +1876,7 @@ def test_delete_transition_route_group_flattened_error(): @pytest.mark.asyncio async def test_delete_transition_route_group_flattened_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1923,14 +1895,13 @@ async def test_delete_transition_route_group_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_transition_route_group_flattened_error_async(): client = TransitionRouteGroupsAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1945,16 +1916,16 @@ async def test_delete_transition_route_group_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( @@ -1964,7 +1935,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = TransitionRouteGroupsClient( @@ -1975,7 +1946,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = TransitionRouteGroupsClient(transport=transport) assert client.transport is transport @@ -1984,13 +1955,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.TransitionRouteGroupsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.TransitionRouteGroupsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2005,8 +1976,8 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() @@ -2014,16 +1985,16 @@ def test_transport_adc(transport_class): def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) assert isinstance(client.transport, transports.TransitionRouteGroupsGrpcTransport,) def test_transition_route_groups_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.TransitionRouteGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2035,7 +2006,7 @@ def test_transition_route_groups_base_transport(): ) as Transport: Transport.return_value = None transport = transports.TransitionRouteGroupsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2052,15 +2023,40 @@ def test_transition_route_groups_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -2076,19 +2072,36 @@ def test_transition_route_groups_base_transport_with_credentials_file(): 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(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.transition_route_groups.transports.TransitionRouteGroupsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.TransitionRouteGroupsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -2099,14 +2112,44 @@ def test_transition_route_groups_auth_adc(): ) -def test_transition_route_groups_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.TransitionRouteGroupsGrpcTransport, + 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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.TransitionRouteGroupsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.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", @@ -2116,6 +2159,123 @@ def test_transition_route_groups_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_transition_route_groups_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,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_old_api_core( + 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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.TransitionRouteGroupsGrpcTransport, grpc_helpers), + (transports.TransitionRouteGroupsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_transition_route_groups_transport_create_channel_user_scopes( + 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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -2126,7 +2286,7 @@ def test_transition_route_groups_transport_auth_adc(): def test_transition_route_groups_grpc_transport_client_cert_source_for_mtls( transport_class, ): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2168,7 +2328,7 @@ def test_transition_route_groups_grpc_transport_client_cert_source_for_mtls( def test_transition_route_groups_host_no_port(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2178,7 +2338,7 @@ def test_transition_route_groups_host_no_port(): def test_transition_route_groups_host_with_port(): client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2234,9 +2394,9 @@ def test_transition_route_groups_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2321,7 +2481,6 @@ def test_flow_path(): location = "clam" agent = "whelk" flow = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}".format( project=project, location=location, agent=agent, flow=flow, ) @@ -2348,7 +2507,6 @@ def test_intent_path(): location = "nautilus" agent = "scallop" intent = "abalone" - expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format( project=project, location=location, agent=agent, intent=intent, ) @@ -2376,7 +2534,6 @@ def test_page_path(): agent = "cuttlefish" flow = "mussel" page = "winkle" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/pages/{page}".format( project=project, location=location, agent=agent, flow=flow, page=page, ) @@ -2405,7 +2562,6 @@ def test_transition_route_group_path(): agent = "oyster" flow = "nudibranch" transition_route_group = "cuttlefish" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/transitionRouteGroups/{transition_route_group}".format( project=project, location=location, @@ -2439,7 +2595,6 @@ def test_webhook_path(): location = "clam" agent = "whelk" webhook = "octopus" - expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2463,7 +2618,6 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2484,7 +2638,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = TransitionRouteGroupsClient.common_folder_path(folder) assert expected == actual @@ -2503,7 +2656,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = TransitionRouteGroupsClient.common_organization_path(organization) assert expected == actual @@ -2522,7 +2674,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = TransitionRouteGroupsClient.common_project_path(project) assert expected == actual @@ -2542,7 +2693,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2569,7 +2719,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.TransitionRouteGroupsTransport, "_prep_wrapped_messages" ) as prep: client = TransitionRouteGroupsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2578,6 +2728,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = TransitionRouteGroupsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py index d940baa7..e23a6cf4 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_versions.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import future 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 operation_async # type: ignore from google.api_core import operations_v1 -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.versions import VersionsAsyncClient 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 ( + _API_CORE_VERSION, +) +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 from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -105,7 +134,7 @@ def test_versions_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) def test_versions_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_versions_client_get_transport_class(): def test_versions_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(VersionsClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -426,7 +455,7 @@ def test_list_versions( transport: str = "grpc", request_type=version.ListVersionsRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -439,19 +468,15 @@ def test_list_versions( call.return_value = version.ListVersionsResponse( next_page_token="next_page_token_value", ) - response = client.list_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.ListVersionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVersionsPager) - assert response.next_page_token == "next_page_token_value" @@ -463,7 +488,7 @@ def test_list_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -471,7 +496,6 @@ def test_list_versions_empty_call(): client.list_versions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.ListVersionsRequest() @@ -480,7 +504,7 @@ async def test_list_versions_async( transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -493,18 +517,15 @@ async def test_list_versions_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( version.ListVersionsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_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.ListVersionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListVersionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -514,17 +535,17 @@ async def test_list_versions_async_from_dict(): def test_list_versions_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_versions), "__call__") as call: call.return_value = version.ListVersionsResponse() - client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -539,11 +560,12 @@ def test_list_versions_field_headers(): @pytest.mark.asyncio async def test_list_versions_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.ListVersionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -551,7 +573,6 @@ async def test_list_versions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( version.ListVersionsResponse() ) - await client.list_versions(request) # Establish that the underlying gRPC stub method was called. @@ -565,13 +586,12 @@ async def test_list_versions_field_headers_async(): def test_list_versions_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.list_versions), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = version.ListVersionsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_versions(parent="parent_value",) @@ -580,12 +600,11 @@ def test_list_versions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_versions_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -597,7 +616,7 @@ def test_list_versions_flattened_error(): @pytest.mark.asyncio async def test_list_versions_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.list_versions), "__call__") as call: @@ -615,13 +634,12 @@ async def test_list_versions_flattened_async(): # 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_versions_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -632,7 +650,7 @@ async def test_list_versions_flattened_error_async(): def test_list_versions_pager(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + 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.list_versions), "__call__") as call: @@ -666,7 +684,7 @@ def test_list_versions_pager(): def test_list_versions_pages(): - client = VersionsClient(credentials=credentials.AnonymousCredentials,) + 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.list_versions), "__call__") as call: @@ -692,7 +710,7 @@ def test_list_versions_pages(): @pytest.mark.asyncio async def test_list_versions_async_pager(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -725,7 +743,7 @@ async def test_list_versions_async_pager(): @pytest.mark.asyncio async def test_list_versions_async_pages(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -755,7 +773,7 @@ async def test_list_versions_async_pages(): def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -771,25 +789,18 @@ def test_get_version(transport: str = "grpc", request_type=version.GetVersionReq description="description_value", state=version.Version.State.RUNNING, ) - response = client.get_version(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.GetVersionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == version.Version.State.RUNNING @@ -801,7 +812,7 @@ def test_get_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -809,7 +820,6 @@ def test_get_version_empty_call(): client.get_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() @@ -818,7 +828,7 @@ async def test_get_version_async( transport: str = "grpc_asyncio", request_type=version.GetVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -836,24 +846,18 @@ async def test_get_version_async( state=version.Version.State.RUNNING, ) ) - response = await client.get_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.GetVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == version.Version.State.RUNNING @@ -863,17 +867,17 @@ async def test_get_version_async_from_dict(): def test_get_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = version.Version() - client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -888,17 +892,17 @@ def test_get_version_field_headers(): @pytest.mark.asyncio async def test_get_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.GetVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_version), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) - await client.get_version(request) # Establish that the underlying gRPC stub method was called. @@ -912,13 +916,12 @@ async def test_get_version_field_headers_async(): def test_get_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.get_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = version.Version() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_version(name="name_value",) @@ -927,12 +930,11 @@ def test_get_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -944,7 +946,7 @@ def test_get_version_flattened_error(): @pytest.mark.asyncio async def test_get_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.get_version), "__call__") as call: @@ -960,13 +962,12 @@ async def test_get_version_flattened_async(): # 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_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -980,7 +981,7 @@ def test_create_version( transport: str = "grpc", request_type=gcdc_version.CreateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -991,13 +992,11 @@ def test_create_version( with mock.patch.object(type(client.transport.create_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -1012,7 +1011,7 @@ def test_create_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1020,7 +1019,6 @@ def test_create_version_empty_call(): client.create_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() @@ -1029,7 +1027,7 @@ async def test_create_version_async( transport: str = "grpc_asyncio", request_type=gcdc_version.CreateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1042,13 +1040,11 @@ async def test_create_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.CreateVersionRequest() # Establish that the response is the type that we expect. @@ -1061,17 +1057,17 @@ async def test_create_version_async_from_dict(): def test_create_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1086,11 +1082,12 @@ def test_create_version_field_headers(): @pytest.mark.asyncio async def test_create_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.CreateVersionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1098,7 +1095,6 @@ async def test_create_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_version(request) # Establish that the underlying gRPC stub method was called. @@ -1112,13 +1108,12 @@ async def test_create_version_field_headers_async(): def test_create_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.create_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_version( @@ -1129,14 +1124,12 @@ def test_create_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].version == gcdc_version.Version(name="name_value") def test_create_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1150,7 +1143,7 @@ def test_create_version_flattened_error(): @pytest.mark.asyncio async def test_create_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.create_version), "__call__") as call: @@ -1170,15 +1163,13 @@ async def test_create_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].version == gcdc_version.Version(name="name_value") @pytest.mark.asyncio async def test_create_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1194,7 +1185,7 @@ def test_update_version( transport: str = "grpc", request_type=gcdc_version.UpdateVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1210,25 +1201,18 @@ def test_update_version( description="description_value", state=gcdc_version.Version.State.RUNNING, ) - response = client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_version.Version.State.RUNNING @@ -1240,7 +1224,7 @@ def test_update_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1248,7 +1232,6 @@ def test_update_version_empty_call(): client.update_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() @@ -1257,7 +1240,7 @@ async def test_update_version_async( transport: str = "grpc_asyncio", request_type=gcdc_version.UpdateVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1275,24 +1258,18 @@ async def test_update_version_async( state=gcdc_version.Version.State.RUNNING, ) ) - response = await client.update_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_version.UpdateVersionRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_version.Version) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.description == "description_value" - assert response.state == gcdc_version.Version.State.RUNNING @@ -1302,17 +1279,17 @@ async def test_update_version_async_from_dict(): def test_update_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.UpdateVersionRequest() + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_version), "__call__") as call: call.return_value = gcdc_version.Version() - client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1329,11 +1306,12 @@ def test_update_version_field_headers(): @pytest.mark.asyncio async def test_update_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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 = gcdc_version.UpdateVersionRequest() + request.version.name = "version.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1341,7 +1319,6 @@ async def test_update_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_version.Version() ) - await client.update_version(request) # Establish that the underlying gRPC stub method was called. @@ -1357,32 +1334,29 @@ async def test_update_version_field_headers_async(): def test_update_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.update_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_version.Version() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_version( version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,13 +1364,13 @@ def test_update_version_flattened_error(): client.update_version( gcdc_version.UpdateVersionRequest(), version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.update_version), "__call__") as call: @@ -1410,22 +1384,20 @@ async def test_update_version_flattened_async(): # using the keyword arguments to the method. response = await client.update_version( version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].version == gcdc_version.Version(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1405,7 @@ async def test_update_version_flattened_error_async(): await client.update_version( gcdc_version.UpdateVersionRequest(), version=gcdc_version.Version(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1441,7 +1413,7 @@ def test_delete_version( transport: str = "grpc", request_type=version.DeleteVersionRequest ): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1452,13 +1424,11 @@ def test_delete_version( with mock.patch.object(type(client.transport.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_version(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.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1473,7 +1443,7 @@ def test_delete_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1481,7 +1451,6 @@ def test_delete_version_empty_call(): client.delete_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.DeleteVersionRequest() @@ -1490,7 +1459,7 @@ async def test_delete_version_async( transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1501,13 +1470,11 @@ async def test_delete_version_async( with mock.patch.object(type(client.transport.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.DeleteVersionRequest() # Establish that the response is the type that we expect. @@ -1520,17 +1487,17 @@ async def test_delete_version_async_from_dict(): def test_delete_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = None - client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1545,17 +1512,17 @@ def test_delete_version_field_headers(): @pytest.mark.asyncio async def test_delete_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.DeleteVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_version), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_version(request) # Establish that the underlying gRPC stub method was called. @@ -1569,13 +1536,12 @@ async def test_delete_version_field_headers_async(): def test_delete_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.delete_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_version(name="name_value",) @@ -1584,12 +1550,11 @@ def test_delete_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1601,7 +1566,7 @@ def test_delete_version_flattened_error(): @pytest.mark.asyncio async def test_delete_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.delete_version), "__call__") as call: @@ -1617,13 +1582,12 @@ async def test_delete_version_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1635,7 +1599,7 @@ async def test_delete_version_flattened_error_async(): def test_load_version(transport: str = "grpc", request_type=version.LoadVersionRequest): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1646,13 +1610,11 @@ def test_load_version(transport: str = "grpc", request_type=version.LoadVersionR with mock.patch.object(type(client.transport.load_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.load_version(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.LoadVersionRequest() # Establish that the response is the type that we expect. @@ -1667,7 +1629,7 @@ def test_load_version_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=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1675,7 +1637,6 @@ def test_load_version_empty_call(): client.load_version() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() @@ -1684,7 +1645,7 @@ async def test_load_version_async( transport: str = "grpc_asyncio", request_type=version.LoadVersionRequest ): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1697,13 +1658,11 @@ async def test_load_version_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.load_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == version.LoadVersionRequest() # Establish that the response is the type that we expect. @@ -1716,17 +1675,17 @@ async def test_load_version_async_from_dict(): def test_load_version_field_headers(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.LoadVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.load_version), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.load_version(request) # Establish that the underlying gRPC stub method was called. @@ -1741,11 +1700,12 @@ def test_load_version_field_headers(): @pytest.mark.asyncio async def test_load_version_field_headers_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.LoadVersionRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1753,7 +1713,6 @@ async def test_load_version_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.load_version(request) # Establish that the underlying gRPC stub method was called. @@ -1767,13 +1726,12 @@ async def test_load_version_field_headers_async(): def test_load_version_flattened(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + 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.load_version), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.load_version(name="name_value",) @@ -1782,12 +1740,11 @@ def test_load_version_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_load_version_flattened_error(): - client = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1799,7 +1756,7 @@ def test_load_version_flattened_error(): @pytest.mark.asyncio async def test_load_version_flattened_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + 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.load_version), "__call__") as call: @@ -1817,13 +1774,12 @@ async def test_load_version_flattened_async(): # 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_load_version_flattened_error_async(): - client = VersionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1836,16 +1792,16 @@ async def test_load_version_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1855,7 +1811,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = VersionsClient( @@ -1866,7 +1822,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = VersionsClient(transport=transport) assert client.transport is transport @@ -1875,13 +1831,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.VersionsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.VersionsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1893,23 +1849,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = VersionsClient(credentials=credentials.AnonymousCredentials(),) + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.VersionsGrpcTransport,) def test_versions_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1921,7 +1877,7 @@ def test_versions_base_transport(): ) as Transport: Transport.return_value = None transport = transports.VersionsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1944,15 +1900,40 @@ 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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1968,19 +1949,36 @@ def test_versions_base_transport_with_credentials_file(): def test_versions_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.VersionsTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1991,14 +1989,38 @@ def test_versions_auth_adc(): ) -def test_versions_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.VersionsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -2008,12 +2030,123 @@ def test_versions_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_versions_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,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VersionsGrpcTransport, grpc_helpers), + (transports.VersionsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_versions_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], ) def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -2055,7 +2188,7 @@ def test_versions_grpc_transport_client_cert_source_for_mtls(transport_class): def test_versions_host_no_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2065,7 +2198,7 @@ def test_versions_host_no_port(): def test_versions_host_with_port(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2116,9 +2249,9 @@ def test_versions_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -2197,7 +2330,7 @@ def test_versions_transport_channel_mtls_with_adc(transport_class): def test_versions_grpc_lro_client(): client = VersionsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2210,7 +2343,7 @@ def test_versions_grpc_lro_client(): def test_versions_grpc_lro_async_client(): client = VersionsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2227,7 +2360,6 @@ def test_version_path(): agent = "whelk" flow = "octopus" version = "oyster" - expected = "projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}".format( project=project, location=location, agent=agent, flow=flow, version=version, ) @@ -2252,7 +2384,6 @@ def test_parse_version_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2273,7 +2404,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = VersionsClient.common_folder_path(folder) assert expected == actual @@ -2292,7 +2422,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = VersionsClient.common_organization_path(organization) assert expected == actual @@ -2311,7 +2440,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = VersionsClient.common_project_path(project) assert expected == actual @@ -2331,7 +2459,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "cuttlefish" location = "mussel" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2358,7 +2485,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.VersionsTransport, "_prep_wrapped_messages" ) as prep: client = VersionsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2367,6 +2494,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = VersionsClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py b/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py index 818a245c..54676cb7 100644 --- a/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py +++ b/tests/unit/gapic/dialogflowcx_v3beta1/test_webhooks.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,23 +23,53 @@ import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule -from google import auth + from google.api_core import client_options -from google.api_core import exceptions +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.dialogflowcx_v3beta1.services.webhooks import WebhooksAsyncClient 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 ( + _API_CORE_VERSION, +) +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 -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and 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", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [WebhooksClient, WebhooksAsyncClient,]) def test_webhooks_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_webhooks_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [WebhooksClient, WebhooksAsyncClient,]) def test_webhooks_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -144,7 +173,7 @@ def test_webhooks_client_get_transport_class(): def test_webhooks_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(WebhooksClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -420,7 +449,7 @@ def test_list_webhooks( transport: str = "grpc", request_type=webhook.ListWebhooksRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -433,19 +462,15 @@ def test_list_webhooks( call.return_value = webhook.ListWebhooksResponse( next_page_token="next_page_token_value", ) - response = client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListWebhooksPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_webhooks_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -465,7 +490,6 @@ def test_list_webhooks_empty_call(): client.list_webhooks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() @@ -474,7 +498,7 @@ async def test_list_webhooks_async( transport: str = "grpc_asyncio", request_type=webhook.ListWebhooksRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -487,18 +511,15 @@ async def test_list_webhooks_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( webhook.ListWebhooksResponse(next_page_token="next_page_token_value",) ) - response = await client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.ListWebhooksRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListWebhooksAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_webhooks_async_from_dict(): def test_list_webhooks_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.ListWebhooksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: call.return_value = webhook.ListWebhooksResponse() - client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_webhooks_field_headers(): @pytest.mark.asyncio async def test_list_webhooks_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.ListWebhooksRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_webhooks_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( webhook.ListWebhooksResponse() ) - await client.list_webhooks(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_webhooks_field_headers_async(): def test_list_webhooks_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = webhook.ListWebhooksResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_webhooks(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_webhooks_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_webhooks_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -591,7 +610,7 @@ def test_list_webhooks_flattened_error(): @pytest.mark.asyncio async def test_list_webhooks_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_webhooks_flattened_async(): # 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_webhooks_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -626,7 +644,7 @@ async def test_list_webhooks_flattened_error_async(): def test_list_webhooks_pager(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_webhooks_pager(): def test_list_webhooks_pages(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_webhooks), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_webhooks_pages(): @pytest.mark.asyncio async def test_list_webhooks_async_pager(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +737,7 @@ async def test_list_webhooks_async_pager(): @pytest.mark.asyncio async def test_list_webhooks_async_pages(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials,) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -749,7 +767,7 @@ async def test_list_webhooks_async_pages(): def test_get_webhook(transport: str = "grpc", request_type=webhook.GetWebhookRequest): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -765,23 +783,17 @@ def test_get_webhook(transport: str = "grpc", request_type=webhook.GetWebhookReq disabled=True, generic_web_service=webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.get_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -793,7 +805,7 @@ def test_get_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -801,7 +813,6 @@ def test_get_webhook_empty_call(): client.get_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() @@ -810,7 +821,7 @@ async def test_get_webhook_async( transport: str = "grpc_asyncio", request_type=webhook.GetWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -825,22 +836,17 @@ async def test_get_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.get_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.GetWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -850,17 +856,17 @@ async def test_get_webhook_async_from_dict(): def test_get_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.GetWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: call.return_value = webhook.Webhook() - client.get_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -875,17 +881,17 @@ def test_get_webhook_field_headers(): @pytest.mark.asyncio async def test_get_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.GetWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(webhook.Webhook()) - await client.get_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -899,13 +905,12 @@ async def test_get_webhook_field_headers_async(): def test_get_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_webhook(name="name_value",) @@ -914,12 +919,11 @@ def test_get_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -931,7 +935,7 @@ def test_get_webhook_flattened_error(): @pytest.mark.asyncio async def test_get_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_webhook), "__call__") as call: @@ -947,13 +951,12 @@ async def test_get_webhook_flattened_async(): # 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_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -967,7 +970,7 @@ def test_create_webhook( transport: str = "grpc", request_type=gcdc_webhook.CreateWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -983,23 +986,17 @@ def test_create_webhook( disabled=True, generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.create_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1011,7 +1008,7 @@ def test_create_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1019,7 +1016,6 @@ def test_create_webhook_empty_call(): client.create_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() @@ -1028,7 +1024,7 @@ async def test_create_webhook_async( transport: str = "grpc_asyncio", request_type=gcdc_webhook.CreateWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1043,22 +1039,17 @@ async def test_create_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.create_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.CreateWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1068,17 +1059,17 @@ async def test_create_webhook_async_from_dict(): def test_create_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = gcdc_webhook.CreateWebhookRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: call.return_value = gcdc_webhook.Webhook() - client.create_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1093,11 +1084,12 @@ def test_create_webhook_field_headers(): @pytest.mark.asyncio async def test_create_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = gcdc_webhook.CreateWebhookRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1105,7 +1097,6 @@ async def test_create_webhook_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_webhook.Webhook() ) - await client.create_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1119,13 +1110,12 @@ async def test_create_webhook_field_headers_async(): def test_create_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_webhook( @@ -1136,14 +1126,12 @@ def test_create_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") def test_create_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1157,7 +1145,7 @@ def test_create_webhook_flattened_error(): @pytest.mark.asyncio async def test_create_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_webhook), "__call__") as call: @@ -1177,15 +1165,13 @@ async def test_create_webhook_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") @pytest.mark.asyncio async def test_create_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1201,7 +1187,7 @@ def test_update_webhook( transport: str = "grpc", request_type=gcdc_webhook.UpdateWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1217,23 +1203,17 @@ def test_update_webhook( disabled=True, generic_web_service=gcdc_webhook.Webhook.GenericWebService(uri="uri_value"), ) - response = client.update_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1245,7 +1225,7 @@ def test_update_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1253,7 +1233,6 @@ def test_update_webhook_empty_call(): client.update_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() @@ -1262,7 +1241,7 @@ async def test_update_webhook_async( transport: str = "grpc_asyncio", request_type=gcdc_webhook.UpdateWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1277,22 +1256,17 @@ async def test_update_webhook_async( name="name_value", display_name="display_name_value", disabled=True, ) ) - response = await client.update_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcdc_webhook.UpdateWebhookRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcdc_webhook.Webhook) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.disabled is True @@ -1302,17 +1276,17 @@ async def test_update_webhook_async_from_dict(): def test_update_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = gcdc_webhook.UpdateWebhookRequest() + request.webhook.name = "webhook.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: call.return_value = gcdc_webhook.Webhook() - client.update_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1329,11 +1303,12 @@ def test_update_webhook_field_headers(): @pytest.mark.asyncio async def test_update_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = gcdc_webhook.UpdateWebhookRequest() + request.webhook.name = "webhook.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1341,7 +1316,6 @@ async def test_update_webhook_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcdc_webhook.Webhook() ) - await client.update_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1357,32 +1331,29 @@ async def test_update_webhook_field_headers_async(): def test_update_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcdc_webhook.Webhook() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_webhook( webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1390,13 +1361,13 @@ def test_update_webhook_flattened_error(): client.update_webhook( gcdc_webhook.UpdateWebhookRequest(), webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_webhook), "__call__") as call: @@ -1410,22 +1381,20 @@ async def test_update_webhook_flattened_async(): # using the keyword arguments to the method. response = await client.update_webhook( webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].webhook == gcdc_webhook.Webhook(name="name_value") - - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1402,7 @@ async def test_update_webhook_flattened_error_async(): await client.update_webhook( gcdc_webhook.UpdateWebhookRequest(), webhook=gcdc_webhook.Webhook(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1441,7 +1410,7 @@ def test_delete_webhook( transport: str = "grpc", request_type=webhook.DeleteWebhookRequest ): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1452,13 +1421,11 @@ def test_delete_webhook( with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() # Establish that the response is the type that we expect. @@ -1473,7 +1440,7 @@ def test_delete_webhook_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 = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1481,7 +1448,6 @@ def test_delete_webhook_empty_call(): client.delete_webhook() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() @@ -1490,7 +1456,7 @@ async def test_delete_webhook_async( transport: str = "grpc_asyncio", request_type=webhook.DeleteWebhookRequest ): client = WebhooksAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1501,13 +1467,11 @@ async def test_delete_webhook_async( with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == webhook.DeleteWebhookRequest() # Establish that the response is the type that we expect. @@ -1520,17 +1484,17 @@ async def test_delete_webhook_async_from_dict(): def test_delete_webhook_field_headers(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(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 = webhook.DeleteWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: call.return_value = None - client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1545,17 +1509,17 @@ def test_delete_webhook_field_headers(): @pytest.mark.asyncio async def test_delete_webhook_field_headers_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(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 = webhook.DeleteWebhookRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_webhook(request) # Establish that the underlying gRPC stub method was called. @@ -1569,13 +1533,12 @@ async def test_delete_webhook_field_headers_async(): def test_delete_webhook_flattened(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_webhook(name="name_value",) @@ -1584,12 +1547,11 @@ def test_delete_webhook_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_webhook_flattened_error(): - client = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1601,7 +1563,7 @@ def test_delete_webhook_flattened_error(): @pytest.mark.asyncio async def test_delete_webhook_flattened_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_webhook), "__call__") as call: @@ -1617,13 +1579,12 @@ async def test_delete_webhook_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_webhook_flattened_error_async(): - client = WebhooksAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1636,16 +1597,16 @@ async def test_delete_webhook_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( @@ -1655,7 +1616,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = WebhooksClient( @@ -1666,7 +1627,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = WebhooksClient(transport=transport) assert client.transport is transport @@ -1675,13 +1636,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.WebhooksGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.WebhooksGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1693,23 +1654,23 @@ def test_transport_get_channel(): ) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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 = WebhooksClient(credentials=credentials.AnonymousCredentials(),) + client = WebhooksClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.WebhooksGrpcTransport,) def test_webhooks_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.WebhooksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1721,7 +1682,7 @@ def test_webhooks_base_transport(): ) as Transport: Transport.return_value = None transport = transports.WebhooksTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1738,15 +1699,40 @@ def test_webhooks_base_transport(): getattr(transport, method)(request=object()) +@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( - auth, "load_credentials_from_file" + 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 = (credentials.AnonymousCredentials(), 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_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", ) @@ -1762,19 +1748,36 @@ def test_webhooks_base_transport_with_credentials_file(): def test_webhooks_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.dialogflowcx_v3beta1.services.webhooks.transports.WebhooksTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.WebhooksTransport() 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(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) + 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=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_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=( @@ -1785,14 +1788,38 @@ def test_webhooks_auth_adc(): ) -def test_webhooks_transport_auth_adc(): +@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. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.WebhooksGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.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", @@ -1802,12 +1829,123 @@ def test_webhooks_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_webhooks_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,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_old_api_core(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") + + create_channel.assert_called_with( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WebhooksGrpcTransport, grpc_helpers), + (transports.WebhooksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_webhooks_transport_create_channel_user_scopes(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", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.WebhooksGrpcTransport, transports.WebhooksGrpcAsyncIOTransport], ) def test_webhooks_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1849,7 +1987,7 @@ def test_webhooks_grpc_transport_client_cert_source_for_mtls(transport_class): def test_webhooks_host_no_port(): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1859,7 +1997,7 @@ def test_webhooks_host_no_port(): def test_webhooks_host_with_port(): client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1910,9 +2048,9 @@ def test_webhooks_transport_channel_mtls_with_client_cert_source(transport_class mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1989,12 +2127,37 @@ def test_webhooks_transport_channel_mtls_with_adc(transport_class): assert transport.grpc_channel == mock_grpc_channel -def test_webhook_path(): +def test_service_path(): project = "squid" location = "clam" - agent = "whelk" - webhook = "octopus" + namespace = "whelk" + service = "octopus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = WebhooksClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", + } + path = WebhooksClient.service_path(**expected) + # Check that the path construction is reversible. + actual = WebhooksClient.parse_service_path(path) + assert expected == actual + + +def test_webhook_path(): + project = "winkle" + location = "nautilus" + agent = "scallop" + webhook = "abalone" expected = "projects/{project}/locations/{location}/agents/{agent}/webhooks/{webhook}".format( project=project, location=location, agent=agent, webhook=webhook, ) @@ -2004,10 +2167,10 @@ def test_webhook_path(): def test_parse_webhook_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "agent": "cuttlefish", - "webhook": "mussel", + "project": "squid", + "location": "clam", + "agent": "whelk", + "webhook": "octopus", } path = WebhooksClient.webhook_path(**expected) @@ -2017,8 +2180,7 @@ def test_parse_webhook_path(): def test_common_billing_account_path(): - billing_account = "winkle" - + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2028,7 +2190,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = WebhooksClient.common_billing_account_path(**expected) @@ -2038,8 +2200,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" - + folder = "cuttlefish" expected = "folders/{folder}".format(folder=folder,) actual = WebhooksClient.common_folder_path(folder) assert expected == actual @@ -2047,7 +2208,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = WebhooksClient.common_folder_path(**expected) @@ -2057,8 +2218,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" - + organization = "winkle" expected = "organizations/{organization}".format(organization=organization,) actual = WebhooksClient.common_organization_path(organization) assert expected == actual @@ -2066,7 +2226,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = WebhooksClient.common_organization_path(**expected) @@ -2076,8 +2236,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" - + project = "scallop" expected = "projects/{project}".format(project=project,) actual = WebhooksClient.common_project_path(project) assert expected == actual @@ -2085,7 +2244,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = WebhooksClient.common_project_path(**expected) @@ -2095,9 +2254,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" - + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2107,8 +2265,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = WebhooksClient.common_location_path(**expected) @@ -2124,7 +2282,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.WebhooksTransport, "_prep_wrapped_messages" ) as prep: client = WebhooksClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2133,6 +2291,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = WebhooksClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)