diff --git a/docs/dialogflow_v2/agents.rst b/docs/dialogflow_v2/agents.rst index 63897cb22..8661ecd44 100644 --- a/docs/dialogflow_v2/agents.rst +++ b/docs/dialogflow_v2/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/answer_records.rst b/docs/dialogflow_v2/answer_records.rst index 02a390a71..20345f618 100644 --- a/docs/dialogflow_v2/answer_records.rst +++ b/docs/dialogflow_v2/answer_records.rst @@ -5,7 +5,6 @@ AnswerRecords :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.answer_records.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/contexts.rst b/docs/dialogflow_v2/contexts.rst index 2f4c1efd7..ab27d7b1e 100644 --- a/docs/dialogflow_v2/contexts.rst +++ b/docs/dialogflow_v2/contexts.rst @@ -5,7 +5,6 @@ Contexts :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.contexts.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/conversation_profiles.rst b/docs/dialogflow_v2/conversation_profiles.rst index 85eaab68d..e5c4cda45 100644 --- a/docs/dialogflow_v2/conversation_profiles.rst +++ b/docs/dialogflow_v2/conversation_profiles.rst @@ -5,7 +5,6 @@ ConversationProfiles :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.conversation_profiles.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/conversations.rst b/docs/dialogflow_v2/conversations.rst index 72a2eb66c..a288e3783 100644 --- a/docs/dialogflow_v2/conversations.rst +++ b/docs/dialogflow_v2/conversations.rst @@ -5,7 +5,6 @@ Conversations :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.conversations.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/documents.rst b/docs/dialogflow_v2/documents.rst index fa18a2320..c95415ace 100644 --- a/docs/dialogflow_v2/documents.rst +++ b/docs/dialogflow_v2/documents.rst @@ -5,7 +5,6 @@ Documents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.documents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/entity_types.rst b/docs/dialogflow_v2/entity_types.rst index 821b7fd71..82634156b 100644 --- a/docs/dialogflow_v2/entity_types.rst +++ b/docs/dialogflow_v2/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/environments.rst b/docs/dialogflow_v2/environments.rst index 3e769ee5d..e0ca6f7f7 100644 --- a/docs/dialogflow_v2/environments.rst +++ b/docs/dialogflow_v2/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.environments.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/fulfillments.rst b/docs/dialogflow_v2/fulfillments.rst new file mode 100644 index 000000000..27f77aa3a --- /dev/null +++ b/docs/dialogflow_v2/fulfillments.rst @@ -0,0 +1,6 @@ +Fulfillments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2.services.fulfillments + :members: + :inherited-members: diff --git a/docs/dialogflow_v2/intents.rst b/docs/dialogflow_v2/intents.rst index c2a444ebf..8418cb20d 100644 --- a/docs/dialogflow_v2/intents.rst +++ b/docs/dialogflow_v2/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/knowledge_bases.rst b/docs/dialogflow_v2/knowledge_bases.rst index d3371043f..7440330af 100644 --- a/docs/dialogflow_v2/knowledge_bases.rst +++ b/docs/dialogflow_v2/knowledge_bases.rst @@ -5,7 +5,6 @@ KnowledgeBases :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.knowledge_bases.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/participants.rst b/docs/dialogflow_v2/participants.rst index 9f5eecedb..6ce8a2c52 100644 --- a/docs/dialogflow_v2/participants.rst +++ b/docs/dialogflow_v2/participants.rst @@ -5,7 +5,6 @@ Participants :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.participants.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/services.rst b/docs/dialogflow_v2/services.rst index 66405aac5..8bdbdfe41 100644 --- a/docs/dialogflow_v2/services.rst +++ b/docs/dialogflow_v2/services.rst @@ -11,8 +11,10 @@ Services for Google Cloud Dialogflow v2 API documents entity_types environments + fulfillments intents knowledge_bases participants session_entity_types sessions + versions diff --git a/docs/dialogflow_v2/session_entity_types.rst b/docs/dialogflow_v2/session_entity_types.rst index a3cfccbbd..e1d7bd321 100644 --- a/docs/dialogflow_v2/session_entity_types.rst +++ b/docs/dialogflow_v2/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2.services.session_entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2/versions.rst b/docs/dialogflow_v2/versions.rst new file mode 100644 index 000000000..af34a4719 --- /dev/null +++ b/docs/dialogflow_v2/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.versions.pagers + :members: + :inherited-members: diff --git a/docs/dialogflow_v2beta1/agents.rst b/docs/dialogflow_v2beta1/agents.rst index 057032e4a..154fdf432 100644 --- a/docs/dialogflow_v2beta1/agents.rst +++ b/docs/dialogflow_v2beta1/agents.rst @@ -5,7 +5,6 @@ Agents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.agents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/answer_records.rst b/docs/dialogflow_v2beta1/answer_records.rst index 26d58d618..1f890c79c 100644 --- a/docs/dialogflow_v2beta1/answer_records.rst +++ b/docs/dialogflow_v2beta1/answer_records.rst @@ -5,7 +5,6 @@ AnswerRecords :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.answer_records.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/contexts.rst b/docs/dialogflow_v2beta1/contexts.rst index 0568b2019..e6be19355 100644 --- a/docs/dialogflow_v2beta1/contexts.rst +++ b/docs/dialogflow_v2beta1/contexts.rst @@ -5,7 +5,6 @@ Contexts :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.contexts.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/conversation_profiles.rst b/docs/dialogflow_v2beta1/conversation_profiles.rst index f3ecaaa53..959fe3698 100644 --- a/docs/dialogflow_v2beta1/conversation_profiles.rst +++ b/docs/dialogflow_v2beta1/conversation_profiles.rst @@ -5,7 +5,6 @@ ConversationProfiles :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.conversation_profiles.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/conversations.rst b/docs/dialogflow_v2beta1/conversations.rst index fda02a6a1..60267bd79 100644 --- a/docs/dialogflow_v2beta1/conversations.rst +++ b/docs/dialogflow_v2beta1/conversations.rst @@ -5,7 +5,6 @@ Conversations :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.conversations.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/documents.rst b/docs/dialogflow_v2beta1/documents.rst index 9516f4254..7151feda6 100644 --- a/docs/dialogflow_v2beta1/documents.rst +++ b/docs/dialogflow_v2beta1/documents.rst @@ -5,7 +5,6 @@ Documents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.documents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/entity_types.rst b/docs/dialogflow_v2beta1/entity_types.rst index f7c940846..99defb836 100644 --- a/docs/dialogflow_v2beta1/entity_types.rst +++ b/docs/dialogflow_v2beta1/entity_types.rst @@ -5,7 +5,6 @@ EntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/environments.rst b/docs/dialogflow_v2beta1/environments.rst index f55d2c24d..3c4d6f333 100644 --- a/docs/dialogflow_v2beta1/environments.rst +++ b/docs/dialogflow_v2beta1/environments.rst @@ -5,7 +5,6 @@ Environments :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.environments.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/fulfillments.rst b/docs/dialogflow_v2beta1/fulfillments.rst new file mode 100644 index 000000000..33be7d8a0 --- /dev/null +++ b/docs/dialogflow_v2beta1/fulfillments.rst @@ -0,0 +1,6 @@ +Fulfillments +------------------------------ + +.. automodule:: google.cloud.dialogflow_v2beta1.services.fulfillments + :members: + :inherited-members: diff --git a/docs/dialogflow_v2beta1/intents.rst b/docs/dialogflow_v2beta1/intents.rst index 2af6dbe49..50e85e80d 100644 --- a/docs/dialogflow_v2beta1/intents.rst +++ b/docs/dialogflow_v2beta1/intents.rst @@ -5,7 +5,6 @@ Intents :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.intents.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/knowledge_bases.rst b/docs/dialogflow_v2beta1/knowledge_bases.rst index 7d2696d24..70e0d5ab6 100644 --- a/docs/dialogflow_v2beta1/knowledge_bases.rst +++ b/docs/dialogflow_v2beta1/knowledge_bases.rst @@ -5,7 +5,6 @@ KnowledgeBases :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.knowledge_bases.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/participants.rst b/docs/dialogflow_v2beta1/participants.rst index 61590eb9d..b2a73ebe3 100644 --- a/docs/dialogflow_v2beta1/participants.rst +++ b/docs/dialogflow_v2beta1/participants.rst @@ -5,7 +5,6 @@ Participants :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.participants.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/services.rst b/docs/dialogflow_v2beta1/services.rst index 209363e0e..dc7790aa3 100644 --- a/docs/dialogflow_v2beta1/services.rst +++ b/docs/dialogflow_v2beta1/services.rst @@ -11,8 +11,10 @@ Services for Google Cloud Dialogflow v2beta1 API documents entity_types environments + fulfillments intents knowledge_bases participants session_entity_types sessions + versions diff --git a/docs/dialogflow_v2beta1/session_entity_types.rst b/docs/dialogflow_v2beta1/session_entity_types.rst index 113b7acfb..4fe3bcb31 100644 --- a/docs/dialogflow_v2beta1/session_entity_types.rst +++ b/docs/dialogflow_v2beta1/session_entity_types.rst @@ -5,7 +5,6 @@ SessionEntityTypes :members: :inherited-members: - .. automodule:: google.cloud.dialogflow_v2beta1.services.session_entity_types.pagers :members: :inherited-members: diff --git a/docs/dialogflow_v2beta1/versions.rst b/docs/dialogflow_v2beta1/versions.rst new file mode 100644 index 000000000..c74ba0edf --- /dev/null +++ b/docs/dialogflow_v2beta1/versions.rst @@ -0,0 +1,10 @@ +Versions +-------------------------- + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2beta1.services.versions.pagers + :members: + :inherited-members: diff --git a/examples/feature_fragments b/examples/feature_fragments new file mode 100644 index 000000000..7d1b62477 --- /dev/null +++ b/examples/feature_fragments @@ -0,0 +1,14 @@ + + + + + + + + + + + + + +} diff --git a/google/cloud/dialogflow/__init__.py b/google/cloud/dialogflow/__init__.py index a766e6b13..2e7f45779 100644 --- a/google/cloud/dialogflow/__init__.py +++ b/google/cloud/dialogflow/__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,71 @@ # limitations under the License. # -from google.cloud.dialogflow_v2.services.agents.async_client import AgentsAsyncClient from google.cloud.dialogflow_v2.services.agents.client import AgentsClient -from google.cloud.dialogflow_v2.services.answer_records.async_client import ( - AnswerRecordsAsyncClient, -) +from google.cloud.dialogflow_v2.services.agents.async_client import AgentsAsyncClient from google.cloud.dialogflow_v2.services.answer_records.client import ( AnswerRecordsClient, ) -from google.cloud.dialogflow_v2.services.contexts.async_client import ( - ContextsAsyncClient, +from google.cloud.dialogflow_v2.services.answer_records.async_client import ( + AnswerRecordsAsyncClient, ) from google.cloud.dialogflow_v2.services.contexts.client import ContextsClient -from google.cloud.dialogflow_v2.services.conversation_profiles.async_client import ( - ConversationProfilesAsyncClient, +from google.cloud.dialogflow_v2.services.contexts.async_client import ( + ContextsAsyncClient, ) from google.cloud.dialogflow_v2.services.conversation_profiles.client import ( ConversationProfilesClient, ) +from google.cloud.dialogflow_v2.services.conversation_profiles.async_client import ( + ConversationProfilesAsyncClient, +) +from google.cloud.dialogflow_v2.services.conversations.client import ConversationsClient from google.cloud.dialogflow_v2.services.conversations.async_client import ( ConversationsAsyncClient, ) -from google.cloud.dialogflow_v2.services.conversations.client import ConversationsClient +from google.cloud.dialogflow_v2.services.documents.client import DocumentsClient from google.cloud.dialogflow_v2.services.documents.async_client import ( DocumentsAsyncClient, ) -from google.cloud.dialogflow_v2.services.documents.client import DocumentsClient +from google.cloud.dialogflow_v2.services.entity_types.client import EntityTypesClient from google.cloud.dialogflow_v2.services.entity_types.async_client import ( EntityTypesAsyncClient, ) -from google.cloud.dialogflow_v2.services.entity_types.client import EntityTypesClient +from google.cloud.dialogflow_v2.services.environments.client import EnvironmentsClient from google.cloud.dialogflow_v2.services.environments.async_client import ( EnvironmentsAsyncClient, ) -from google.cloud.dialogflow_v2.services.environments.client import EnvironmentsClient -from google.cloud.dialogflow_v2.services.intents.async_client import IntentsAsyncClient -from google.cloud.dialogflow_v2.services.intents.client import IntentsClient -from google.cloud.dialogflow_v2.services.knowledge_bases.async_client import ( - KnowledgeBasesAsyncClient, +from google.cloud.dialogflow_v2.services.fulfillments.client import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments.async_client import ( + FulfillmentsAsyncClient, ) +from google.cloud.dialogflow_v2.services.intents.client import IntentsClient +from google.cloud.dialogflow_v2.services.intents.async_client import IntentsAsyncClient from google.cloud.dialogflow_v2.services.knowledge_bases.client import ( KnowledgeBasesClient, ) -from google.cloud.dialogflow_v2.services.participants.async_client import ( - ParticipantsAsyncClient, +from google.cloud.dialogflow_v2.services.knowledge_bases.async_client import ( + KnowledgeBasesAsyncClient, ) from google.cloud.dialogflow_v2.services.participants.client import ParticipantsClient -from google.cloud.dialogflow_v2.services.session_entity_types.async_client import ( - SessionEntityTypesAsyncClient, +from google.cloud.dialogflow_v2.services.participants.async_client import ( + ParticipantsAsyncClient, ) from google.cloud.dialogflow_v2.services.session_entity_types.client import ( SessionEntityTypesClient, ) +from google.cloud.dialogflow_v2.services.session_entity_types.async_client import ( + SessionEntityTypesAsyncClient, +) +from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient from google.cloud.dialogflow_v2.services.sessions.async_client import ( SessionsAsyncClient, ) -from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient +from google.cloud.dialogflow_v2.services.versions.client import VersionsClient +from google.cloud.dialogflow_v2.services.versions.async_client import ( + VersionsAsyncClient, +) + from google.cloud.dialogflow_v2.types.agent import Agent from google.cloud.dialogflow_v2.types.agent import DeleteAgentRequest from google.cloud.dialogflow_v2.types.agent import ExportAgentRequest @@ -90,17 +98,17 @@ from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsRequest from google.cloud.dialogflow_v2.types.answer_record import ListAnswerRecordsResponse from google.cloud.dialogflow_v2.types.answer_record import UpdateAnswerRecordRequest -from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding from google.cloud.dialogflow_v2.types.audio_config import InputAudioConfig from google.cloud.dialogflow_v2.types.audio_config import OutputAudioConfig -from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding from google.cloud.dialogflow_v2.types.audio_config import SpeechContext -from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant from google.cloud.dialogflow_v2.types.audio_config import SpeechToTextConfig from google.cloud.dialogflow_v2.types.audio_config import SpeechWordInfo -from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender from google.cloud.dialogflow_v2.types.audio_config import SynthesizeSpeechConfig from google.cloud.dialogflow_v2.types.audio_config import VoiceSelectionParams +from google.cloud.dialogflow_v2.types.audio_config import AudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import OutputAudioEncoding +from google.cloud.dialogflow_v2.types.audio_config import SpeechModelVariant +from google.cloud.dialogflow_v2.types.audio_config import SsmlVoiceGender from google.cloud.dialogflow_v2.types.context import Context from google.cloud.dialogflow_v2.types.context import CreateContextRequest from google.cloud.dialogflow_v2.types.context import DeleteAllContextsRequest @@ -171,9 +179,19 @@ from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesRequest from google.cloud.dialogflow_v2.types.entity_type import ListEntityTypesResponse from google.cloud.dialogflow_v2.types.entity_type import UpdateEntityTypeRequest +from google.cloud.dialogflow_v2.types.environment import CreateEnvironmentRequest +from google.cloud.dialogflow_v2.types.environment import DeleteEnvironmentRequest from google.cloud.dialogflow_v2.types.environment import Environment +from google.cloud.dialogflow_v2.types.environment import EnvironmentHistory +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentHistoryRequest +from google.cloud.dialogflow_v2.types.environment import GetEnvironmentRequest from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsRequest from google.cloud.dialogflow_v2.types.environment import ListEnvironmentsResponse +from google.cloud.dialogflow_v2.types.environment import TextToSpeechSettings +from google.cloud.dialogflow_v2.types.environment import UpdateEnvironmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import Fulfillment +from google.cloud.dialogflow_v2.types.fulfillment import GetFulfillmentRequest +from google.cloud.dialogflow_v2.types.fulfillment import UpdateFulfillmentRequest from google.cloud.dialogflow_v2.types.human_agent_assistant_event import ( HumanAgentAssistantEvent, ) @@ -185,10 +203,10 @@ from google.cloud.dialogflow_v2.types.intent import GetIntentRequest from google.cloud.dialogflow_v2.types.intent import Intent from google.cloud.dialogflow_v2.types.intent import IntentBatch -from google.cloud.dialogflow_v2.types.intent import IntentView from google.cloud.dialogflow_v2.types.intent import ListIntentsRequest from google.cloud.dialogflow_v2.types.intent import ListIntentsResponse from google.cloud.dialogflow_v2.types.intent import UpdateIntentRequest +from google.cloud.dialogflow_v2.types.intent import IntentView from google.cloud.dialogflow_v2.types.knowledge_base import CreateKnowledgeBaseRequest from google.cloud.dialogflow_v2.types.knowledge_base import DeleteKnowledgeBaseRequest from google.cloud.dialogflow_v2.types.knowledge_base import GetKnowledgeBaseRequest @@ -251,188 +269,216 @@ ) from google.cloud.dialogflow_v2.types.validation_result import ValidationError from google.cloud.dialogflow_v2.types.validation_result import ValidationResult +from google.cloud.dialogflow_v2.types.version import CreateVersionRequest +from google.cloud.dialogflow_v2.types.version import DeleteVersionRequest +from google.cloud.dialogflow_v2.types.version import GetVersionRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsRequest +from google.cloud.dialogflow_v2.types.version import ListVersionsResponse +from google.cloud.dialogflow_v2.types.version import UpdateVersionRequest +from google.cloud.dialogflow_v2.types.version import Version from google.cloud.dialogflow_v2.types.webhook import OriginalDetectIntentRequest from google.cloud.dialogflow_v2.types.webhook import WebhookRequest from google.cloud.dialogflow_v2.types.webhook import WebhookResponse __all__ = ( - "Agent", - "AgentAssistantFeedback", - "AgentAssistantRecord", - "AgentsAsyncClient", "AgentsClient", - "AnalyzeContentRequest", - "AnalyzeContentResponse", - "AnnotatedMessagePart", - "AnswerFeedback", - "AnswerRecord", - "AnswerRecordsAsyncClient", + "AgentsAsyncClient", "AnswerRecordsClient", - "ArticleAnswer", - "AudioEncoding", - "AutomatedAgentConfig", - "AutomatedAgentReply", - "BatchCreateEntitiesRequest", - "BatchDeleteEntitiesRequest", - "BatchDeleteEntityTypesRequest", - "BatchDeleteIntentsRequest", - "BatchUpdateEntitiesRequest", - "BatchUpdateEntityTypesRequest", - "BatchUpdateEntityTypesResponse", - "BatchUpdateIntentsRequest", - "BatchUpdateIntentsResponse", - "CompleteConversationRequest", - "Context", - "ContextsAsyncClient", + "AnswerRecordsAsyncClient", "ContextsClient", - "Conversation", - "ConversationEvent", - "ConversationPhoneNumber", - "ConversationProfile", - "ConversationProfilesAsyncClient", + "ContextsAsyncClient", "ConversationProfilesClient", - "ConversationsAsyncClient", + "ConversationProfilesAsyncClient", "ConversationsClient", - "CreateContextRequest", - "CreateConversationProfileRequest", - "CreateConversationRequest", - "CreateDocumentRequest", - "CreateEntityTypeRequest", - "CreateIntentRequest", - "CreateKnowledgeBaseRequest", - "CreateParticipantRequest", - "CreateSessionEntityTypeRequest", - "DeleteAgentRequest", - "DeleteAllContextsRequest", - "DeleteContextRequest", - "DeleteConversationProfileRequest", - "DeleteDocumentRequest", - "DeleteEntityTypeRequest", - "DeleteIntentRequest", - "DeleteKnowledgeBaseRequest", - "DeleteSessionEntityTypeRequest", - "DetectIntentRequest", - "DetectIntentResponse", - "Document", - "DocumentsAsyncClient", + "ConversationsAsyncClient", "DocumentsClient", - "DtmfParameters", - "EntityType", - "EntityTypeBatch", - "EntityTypesAsyncClient", + "DocumentsAsyncClient", "EntityTypesClient", - "Environment", - "EnvironmentsAsyncClient", + "EntityTypesAsyncClient", "EnvironmentsClient", - "EventInput", + "EnvironmentsAsyncClient", + "FulfillmentsClient", + "FulfillmentsAsyncClient", + "IntentsClient", + "IntentsAsyncClient", + "KnowledgeBasesClient", + "KnowledgeBasesAsyncClient", + "ParticipantsClient", + "ParticipantsAsyncClient", + "SessionEntityTypesClient", + "SessionEntityTypesAsyncClient", + "SessionsClient", + "SessionsAsyncClient", + "VersionsClient", + "VersionsAsyncClient", + "Agent", + "DeleteAgentRequest", "ExportAgentRequest", "ExportAgentResponse", - "FaqAnswer", "GetAgentRequest", - "GetContextRequest", - "GetConversationProfileRequest", - "GetConversationRequest", - "GetDocumentRequest", - "GetEntityTypeRequest", - "GetIntentRequest", - "GetKnowledgeBaseRequest", - "GetParticipantRequest", - "GetSessionEntityTypeRequest", "GetValidationResultRequest", - "HumanAgentAssistantConfig", - "HumanAgentAssistantEvent", - "HumanAgentHandoffConfig", "ImportAgentRequest", - "InputAudioConfig", - "Intent", - "IntentBatch", - "IntentView", - "IntentsAsyncClient", - "IntentsClient", - "KnowledgeBase", - "KnowledgeBasesAsyncClient", - "KnowledgeBasesClient", - "KnowledgeOperationMetadata", + "RestoreAgentRequest", + "SearchAgentsRequest", + "SearchAgentsResponse", + "SetAgentRequest", + "TrainAgentRequest", + "AgentAssistantFeedback", + "AgentAssistantRecord", + "AnswerFeedback", + "AnswerRecord", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", + "UpdateAnswerRecordRequest", + "InputAudioConfig", + "OutputAudioConfig", + "SpeechContext", + "SpeechToTextConfig", + "SpeechWordInfo", + "SynthesizeSpeechConfig", + "VoiceSelectionParams", + "AudioEncoding", + "OutputAudioEncoding", + "SpeechModelVariant", + "SsmlVoiceGender", + "Context", + "CreateContextRequest", + "DeleteAllContextsRequest", + "DeleteContextRequest", + "GetContextRequest", "ListContextsRequest", "ListContextsResponse", - "ListConversationProfilesRequest", - "ListConversationProfilesResponse", + "UpdateContextRequest", + "CompleteConversationRequest", + "Conversation", + "ConversationPhoneNumber", + "CreateConversationRequest", + "GetConversationRequest", "ListConversationsRequest", "ListConversationsResponse", + "ListMessagesRequest", + "ListMessagesResponse", + "ConversationEvent", + "AutomatedAgentConfig", + "ConversationProfile", + "CreateConversationProfileRequest", + "DeleteConversationProfileRequest", + "GetConversationProfileRequest", + "HumanAgentAssistantConfig", + "HumanAgentHandoffConfig", + "ListConversationProfilesRequest", + "ListConversationProfilesResponse", + "LoggingConfig", + "NotificationConfig", + "SuggestionFeature", + "UpdateConversationProfileRequest", + "CreateDocumentRequest", + "DeleteDocumentRequest", + "Document", + "GetDocumentRequest", + "KnowledgeOperationMetadata", "ListDocumentsRequest", "ListDocumentsResponse", + "ReloadDocumentRequest", + "UpdateDocumentRequest", + "BatchCreateEntitiesRequest", + "BatchDeleteEntitiesRequest", + "BatchDeleteEntityTypesRequest", + "BatchUpdateEntitiesRequest", + "BatchUpdateEntityTypesRequest", + "BatchUpdateEntityTypesResponse", + "CreateEntityTypeRequest", + "DeleteEntityTypeRequest", + "EntityType", + "EntityTypeBatch", + "GetEntityTypeRequest", "ListEntityTypesRequest", "ListEntityTypesResponse", + "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", + "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", + "HumanAgentAssistantEvent", + "BatchDeleteIntentsRequest", + "BatchUpdateIntentsRequest", + "BatchUpdateIntentsResponse", + "CreateIntentRequest", + "DeleteIntentRequest", + "GetIntentRequest", + "Intent", + "IntentBatch", "ListIntentsRequest", "ListIntentsResponse", + "UpdateIntentRequest", + "IntentView", + "CreateKnowledgeBaseRequest", + "DeleteKnowledgeBaseRequest", + "GetKnowledgeBaseRequest", + "KnowledgeBase", "ListKnowledgeBasesRequest", "ListKnowledgeBasesResponse", - "ListMessagesRequest", - "ListMessagesResponse", + "UpdateKnowledgeBaseRequest", + "AnalyzeContentRequest", + "AnalyzeContentResponse", + "AnnotatedMessagePart", + "ArticleAnswer", + "AutomatedAgentReply", + "CreateParticipantRequest", + "DtmfParameters", + "FaqAnswer", + "GetParticipantRequest", "ListParticipantsRequest", "ListParticipantsResponse", - "ListSessionEntityTypesRequest", - "ListSessionEntityTypesResponse", - "LoggingConfig", "Message", "MessageAnnotation", - "NotificationConfig", - "OriginalDetectIntentRequest", "OutputAudio", - "OutputAudioConfig", - "OutputAudioEncoding", "Participant", - "ParticipantsAsyncClient", - "ParticipantsClient", + "SuggestArticlesRequest", + "SuggestArticlesResponse", + "SuggestFaqAnswersRequest", + "SuggestFaqAnswersResponse", + "SuggestionResult", + "UpdateParticipantRequest", + "DetectIntentRequest", + "DetectIntentResponse", + "EventInput", "QueryInput", "QueryParameters", "QueryResult", - "ReloadDocumentRequest", - "RestoreAgentRequest", - "SearchAgentsRequest", - "SearchAgentsResponse", "Sentiment", "SentimentAnalysisRequestConfig", "SentimentAnalysisResult", - "SessionEntityType", - "SessionEntityTypesAsyncClient", - "SessionEntityTypesClient", - "SessionsAsyncClient", - "SessionsClient", - "SetAgentRequest", - "SpeechContext", - "SpeechModelVariant", - "SpeechToTextConfig", - "SpeechWordInfo", - "SsmlVoiceGender", "StreamingDetectIntentRequest", "StreamingDetectIntentResponse", "StreamingRecognitionResult", - "SuggestArticlesRequest", - "SuggestArticlesResponse", - "SuggestFaqAnswersRequest", - "SuggestFaqAnswersResponse", - "SuggestionFeature", - "SuggestionResult", - "SynthesizeSpeechConfig", "TextInput", - "TrainAgentRequest", - "UpdateAnswerRecordRequest", - "UpdateContextRequest", - "UpdateConversationProfileRequest", - "UpdateDocumentRequest", - "UpdateEntityTypeRequest", - "UpdateIntentRequest", - "UpdateKnowledgeBaseRequest", - "UpdateParticipantRequest", + "CreateSessionEntityTypeRequest", + "DeleteSessionEntityTypeRequest", + "GetSessionEntityTypeRequest", + "ListSessionEntityTypesRequest", + "ListSessionEntityTypesResponse", + "SessionEntityType", "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", - "VoiceSelectionParams", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", + "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", ) diff --git a/google/cloud/dialogflow_v2/__init__.py b/google/cloud/dialogflow_v2/__init__.py index 1bc06d15b..fb302d1e8 100644 --- a/google/cloud/dialogflow_v2/__init__.py +++ b/google/cloud/dialogflow_v2/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,36 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient 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.versions import VersionsClient +from .services.versions import VersionsAsyncClient + from .types.agent import Agent from .types.agent import DeleteAgentRequest from .types.agent import ExportAgentRequest @@ -47,17 +64,17 @@ from .types.answer_record import ListAnswerRecordsRequest from .types.answer_record import ListAnswerRecordsResponse from .types.answer_record import UpdateAnswerRecordRequest -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 SpeechContext -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechToTextConfig 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.context import Context from .types.context import CreateContextRequest from .types.context import DeleteAllContextsRequest @@ -112,9 +129,19 @@ from .types.entity_type import ListEntityTypesRequest from .types.entity_type import ListEntityTypesResponse from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest from .types.environment import ListEnvironmentsRequest from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest from .types.human_agent_assistant_event import HumanAgentAssistantEvent from .types.intent import BatchDeleteIntentsRequest from .types.intent import BatchUpdateIntentsRequest @@ -124,10 +151,10 @@ from .types.intent import GetIntentRequest from .types.intent import Intent from .types.intent import IntentBatch -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.knowledge_base import CreateKnowledgeBaseRequest from .types.knowledge_base import DeleteKnowledgeBaseRequest from .types.knowledge_base import GetKnowledgeBaseRequest @@ -178,11 +205,17 @@ from .types.session_entity_type import UpdateSessionEntityTypeRequest from .types.validation_result import ValidationError from .types.validation_result import ValidationResult +from .types.version import CreateVersionRequest +from .types.version import DeleteVersionRequest +from .types.version import GetVersionRequest +from .types.version import ListVersionsRequest +from .types.version import ListVersionsResponse +from .types.version import UpdateVersionRequest +from .types.version import Version from .types.webhook import OriginalDetectIntentRequest from .types.webhook import WebhookRequest from .types.webhook import WebhookResponse - __all__ = ( "Agent", "AgentAssistantFeedback", @@ -221,19 +254,23 @@ "CreateConversationRequest", "CreateDocumentRequest", "CreateEntityTypeRequest", + "CreateEnvironmentRequest", "CreateIntentRequest", "CreateKnowledgeBaseRequest", "CreateParticipantRequest", "CreateSessionEntityTypeRequest", + "CreateVersionRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", "DeleteEntityTypeRequest", + "DeleteEnvironmentRequest", "DeleteIntentRequest", "DeleteKnowledgeBaseRequest", "DeleteSessionEntityTypeRequest", + "DeleteVersionRequest", "DetectIntentRequest", "DetectIntentResponse", "Document", @@ -243,22 +280,29 @@ "EntityTypeBatch", "EntityTypesClient", "Environment", + "EnvironmentHistory", "EnvironmentsClient", "EventInput", "ExportAgentRequest", "ExportAgentResponse", "FaqAnswer", + "Fulfillment", + "FulfillmentsClient", "GetAgentRequest", "GetContextRequest", "GetConversationProfileRequest", "GetConversationRequest", "GetDocumentRequest", "GetEntityTypeRequest", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", + "GetFulfillmentRequest", "GetIntentRequest", "GetKnowledgeBaseRequest", "GetParticipantRequest", "GetSessionEntityTypeRequest", "GetValidationResultRequest", + "GetVersionRequest", "HumanAgentAssistantConfig", "HumanAgentAssistantEvent", "HumanAgentHandoffConfig", @@ -269,6 +313,7 @@ "IntentView", "IntentsClient", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -294,6 +339,8 @@ "ListParticipantsResponse", "ListSessionEntityTypesRequest", "ListSessionEntityTypesResponse", + "ListVersionsRequest", + "ListVersionsResponse", "LoggingConfig", "Message", "MessageAnnotation", @@ -334,20 +381,25 @@ "SuggestionResult", "SynthesizeSpeechConfig", "TextInput", + "TextToSpeechSettings", "TrainAgentRequest", "UpdateAnswerRecordRequest", "UpdateContextRequest", "UpdateConversationProfileRequest", "UpdateDocumentRequest", "UpdateEntityTypeRequest", + "UpdateEnvironmentRequest", + "UpdateFulfillmentRequest", "UpdateIntentRequest", "UpdateKnowledgeBaseRequest", "UpdateParticipantRequest", "UpdateSessionEntityTypeRequest", + "UpdateVersionRequest", "ValidationError", "ValidationResult", + "Version", + "VersionsClient", "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", ) diff --git a/google/cloud/dialogflow_v2/gapic_metadata.json b/google/cloud/dialogflow_v2/gapic_metadata.json new file mode 100644 index 000000000..b73c53792 --- /dev/null +++ b/google/cloud/dialogflow_v2/gapic_metadata.json @@ -0,0 +1,1039 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2", + "protoPackage": "google.cloud.dialogflow.v2", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "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": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "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" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "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": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "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" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "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" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/dialogflow_v2/services/__init__.py b/google/cloud/dialogflow_v2/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/cloud/dialogflow_v2/services/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/agents/__init__.py b/google/cloud/dialogflow_v2/services/agents/__init__.py index 4bcbd7ac8..0501fa947 100644 --- a/google/cloud/dialogflow_v2/services/agents/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/agents/async_client.py b/google/cloud/dialogflow_v2/services/agents/async_client.py index 6ebcfe0ba..46e3ad1ca 100644 --- a/google/cloud/dialogflow_v2/services/agents/async_client.py +++ b/google/cloud/dialogflow_v2/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,9 +32,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_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 @@ -52,23 +49,18 @@ class AgentsAsyncClient: agent_path = staticmethod(AgentsClient.agent_path) parse_agent_path = staticmethod(AgentsClient.parse_agent_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) @@ -120,7 +112,7 @@ 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, @@ -157,7 +149,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -187,7 +178,6 @@ async def get_agent( 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 +213,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -267,7 +256,6 @@ async def set_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. @@ -303,7 +291,6 @@ async def set_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -351,7 +338,6 @@ async def delete_agent( 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. @@ -372,7 +358,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -423,7 +408,6 @@ async def search_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. @@ -453,7 +437,6 @@ async def search_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -508,7 +491,6 @@ async def train_agent( 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. @@ -548,7 +530,6 @@ async def train_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -573,8 +554,8 @@ async def train_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. @@ -605,7 +586,6 @@ async def export_agent( 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. @@ -636,7 +616,6 @@ async def export_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -662,7 +641,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. @@ -698,7 +677,6 @@ async def import_agent( request (:class:`google.cloud.dialogflow_v2.types.ImportAgentRequest`): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -725,7 +703,6 @@ async def import_agent( """ # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -749,8 +726,8 @@ async def import_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. @@ -784,7 +761,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflow_v2.types.RestoreAgentRequest`): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -811,7 +787,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, @@ -835,8 +810,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. @@ -858,7 +833,6 @@ async def get_validation_result( request (:class:`google.cloud.dialogflow_v2.types.GetValidationResultRequest`): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -872,7 +846,6 @@ async def get_validation_result( """ # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2/services/agents/client.py b/google/cloud/dialogflow_v2/services/agents/client.py index 56cd648d7..e14e64294 100644 --- a/google/cloud/dialogflow_v2/services/agents/client.py +++ b/google/cloud/dialogflow_v2/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,9 +36,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_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 @@ -232,7 +229,7 @@ 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, @@ -364,7 +361,6 @@ def get_agent( 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. @@ -402,10 +398,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 parent is not None: request.parent = parent @@ -445,7 +439,6 @@ def set_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. @@ -483,10 +476,8 @@ def set_agent( # there are no flattened fields. if not isinstance(request, gcd_agent.SetAgentRequest): request = gcd_agent.SetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -530,7 +521,6 @@ def delete_agent( 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. @@ -553,10 +543,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 parent is not None: request.parent = parent @@ -603,7 +591,6 @@ def search_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. @@ -635,10 +622,8 @@ def search_agents( # there are no flattened fields. if not isinstance(request, agent.SearchAgentsRequest): request = agent.SearchAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -689,7 +674,6 @@ def train_agent( 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. @@ -731,10 +715,8 @@ def train_agent( # there are no flattened fields. if not isinstance(request, agent.TrainAgentRequest): request = agent.TrainAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -755,8 +737,8 @@ def train_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. @@ -787,7 +769,6 @@ def export_agent( 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. @@ -820,10 +801,8 @@ def export_agent( # there are no flattened fields. if not isinstance(request, agent.ExportAgentRequest): request = agent.ExportAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -845,7 +824,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -881,7 +860,6 @@ def import_agent( request (google.cloud.dialogflow_v2.types.ImportAgentRequest): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -908,7 +886,6 @@ def import_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ImportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -933,8 +910,8 @@ def import_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. @@ -968,7 +945,6 @@ def restore_agent( request (google.cloud.dialogflow_v2.types.RestoreAgentRequest): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -995,7 +971,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 @@ -1020,8 +995,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. @@ -1043,7 +1018,6 @@ def get_validation_result( request (google.cloud.dialogflow_v2.types.GetValidationResultRequest): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1057,7 +1031,6 @@ def get_validation_result( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.GetValidationResultRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2/services/agents/pagers.py b/google/cloud/dialogflow_v2/services/agents/pagers.py index edb50660a..862abf538 100644 --- a/google/cloud/dialogflow_v2/services/agents/pagers.py +++ b/google/cloud/dialogflow_v2/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, diff --git a/google/cloud/dialogflow_v2/services/agents/transports/__init__.py b/google/cloud/dialogflow_v2/services/agents/transports/__init__.py index dfed91927..ceadcd3aa 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/agents/transports/base.py b/google/cloud/dialogflow_v2/services/agents/transports/base.py index b41e474a7..e3e6bb8c5 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2/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,24 +13,24 @@ # 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.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -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( @@ -42,6 +41,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.""" @@ -51,21 +61,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 @@ -74,7 +87,7 @@ 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): @@ -88,29 +101,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -153,85 +213,78 @@ def operations_client(self) -> operations_v1.OperationsClient: @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 set_agent( self, - ) -> typing.Callable[ - [gcd_agent.SetAgentRequest], - typing.Union[gcd_agent.Agent, typing.Awaitable[gcd_agent.Agent]], + ) -> Callable[ + [gcd_agent.SetAgentRequest], Union[gcd_agent.Agent, Awaitable[gcd_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 search_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.SearchAgentsRequest], - typing.Union[ - agent.SearchAgentsResponse, typing.Awaitable[agent.SearchAgentsResponse] - ], + Union[agent.SearchAgentsResponse, Awaitable[agent.SearchAgentsResponse]], ]: raise NotImplementedError() @property def train_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.TrainAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: 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 import_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ImportAgentRequest], - 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 get_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetValidationResultRequest], - typing.Union[ + Union[ validation_result.ValidationResult, - typing.Awaitable[validation_result.ValidationResult], + Awaitable[validation_result.ValidationResult], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc.py index 3ace9db2e..281cb014b 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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,15 +13,14 @@ # 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 @@ -30,9 +28,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -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 @@ -180,7 +178,7 @@ def __init__( 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,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, ) @@ -290,7 +290,7 @@ def set_agent(self) -> Callable[[gcd_agent.SetAgentRequest], gcd_agent.Agent]: return self._stubs["set_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. @@ -309,7 +309,7 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -346,7 +346,9 @@ def search_agents( return self._stubs["search_agents"] @property - def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operation]: + def train_agent( + self, + ) -> Callable[[agent.TrainAgentRequest], operations_pb2.Operation]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -368,14 +370,14 @@ def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operatio self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_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 ZIP file. @@ -397,14 +399,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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 import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ImportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -439,14 +441,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_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 ZIP file. @@ -479,7 +481,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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/dialogflow_v2/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py index 22f02de20..9fb73d4fb 100644 --- a/google/cloud/dialogflow_v2/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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,16 +13,15 @@ # 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 @@ -31,9 +29,8 @@ from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result -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, @@ -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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -300,7 +299,7 @@ def set_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. @@ -319,7 +318,7 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -358,7 +357,7 @@ def search_agents( @property def train_agent( self, - ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -380,14 +379,14 @@ def train_agent( self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_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 ZIP file. @@ -409,14 +408,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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 import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -451,14 +450,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_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 ZIP file. @@ -491,7 +490,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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/dialogflow_v2/services/answer_records/__init__.py b/google/cloud/dialogflow_v2/services/answer_records/__init__.py index 7618f55a7..25960120e 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/__init__.py +++ b/google/cloud/dialogflow_v2/services/answer_records/__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 AnswerRecordsClient from .async_client import AnswerRecordsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/google/cloud/dialogflow_v2/services/answer_records/async_client.py index cd5148715..bc6c577bf 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -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 AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport from .client import AnswerRecordsClient @@ -52,31 +49,26 @@ class AnswerRecordsAsyncClient: parse_answer_record_path = staticmethod( AnswerRecordsClient.parse_answer_record_path ) - common_billing_account_path = staticmethod( AnswerRecordsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AnswerRecordsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) parse_common_folder_path = staticmethod( AnswerRecordsClient.parse_common_folder_path ) - common_organization_path = staticmethod( AnswerRecordsClient.common_organization_path ) parse_common_organization_path = staticmethod( AnswerRecordsClient.parse_common_organization_path ) - common_project_path = staticmethod(AnswerRecordsClient.common_project_path) parse_common_project_path = staticmethod( AnswerRecordsClient.parse_common_project_path ) - common_location_path = staticmethod(AnswerRecordsClient.common_location_path) parse_common_location_path = staticmethod( AnswerRecordsClient.parse_common_location_path @@ -130,7 +122,7 @@ def transport(self) -> AnswerRecordsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -167,7 +159,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AnswerRecordsClient( credentials=credentials, transport=transport, @@ -199,7 +190,6 @@ async def list_answer_records( 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. @@ -209,7 +199,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -229,7 +219,6 @@ async def list_answer_records( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -264,7 +253,7 @@ async def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = 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]] = (), @@ -287,7 +276,6 @@ async def update_answer_record( 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. @@ -324,12 +312,11 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -346,7 +333,6 @@ async def update_answer_record( # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/answer_records/client.py b/google/cloud/dialogflow_v2/services/answer_records/client.py index 9940b63f1..e9a231dba 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record -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 AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AnswerRecordsGrpcTransport from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport @@ -234,7 +231,7 @@ 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, AnswerRecordsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -368,7 +365,6 @@ def list_answer_records( 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. @@ -378,7 +374,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -400,10 +396,8 @@ def list_answer_records( # there are no flattened fields. if not isinstance(request, answer_record.ListAnswerRecordsRequest): request = answer_record.ListAnswerRecordsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -434,7 +428,7 @@ def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = 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]] = (), @@ -457,7 +451,6 @@ def update_answer_record( 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. @@ -494,12 +487,11 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -518,10 +510,8 @@ def update_answer_record( # there are no flattened fields. if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): request = gcd_answer_record.UpdateAnswerRecordRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/answer_records/pagers.py b/google/cloud/dialogflow_v2/services/answer_records/pagers.py index 6495fe2db..bc317b432 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/pagers.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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, diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py b/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py index bbb65cf15..e97f4f57d 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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/dialogflow_v2/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2/services/answer_records/transports/base.py index d82b61291..6e3503557 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 AnswerRecordsTransport(abc.ABC): """Abstract transport class for AnswerRecords.""" @@ -47,21 +57,24 @@ class AnswerRecordsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -123,11 +183,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_answer_records( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.ListAnswerRecordsRequest], - typing.Union[ + Union[ answer_record.ListAnswerRecordsResponse, - typing.Awaitable[answer_record.ListAnswerRecordsResponse], + Awaitable[answer_record.ListAnswerRecordsResponse], ], ]: raise NotImplementedError() @@ -135,11 +195,10 @@ def list_answer_records( @property def update_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_answer_record.UpdateAnswerRecordRequest], - typing.Union[ - gcd_answer_record.AnswerRecord, - typing.Awaitable[gcd_answer_record.AnswerRecord], + Union[ + gcd_answer_record.AnswerRecord, Awaitable[gcd_answer_record.AnswerRecord] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py index 38373a7c5..5e7694260 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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,21 +13,19 @@ # 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.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) diff --git a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py index eec5d7448..002c9b9f5 100644 --- a/google/cloud/dialogflow_v2/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/answer_records/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,22 +13,20 @@ # 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.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .grpc import AnswerRecordsGrpcTransport @@ -55,7 +52,7 @@ class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/contexts/__init__.py b/google/cloud/dialogflow_v2/services/contexts/__init__.py index 56b19b0f2..4c5791dcf 100644 --- a/google/cloud/dialogflow_v2/services/contexts/__init__.py +++ b/google/cloud/dialogflow_v2/services/contexts/__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 ContextsClient from .async_client import ContextsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/contexts/async_client.py b/google/cloud/dialogflow_v2/services/contexts/async_client.py index 9c318ef5e..252783364 100644 --- a/google/cloud/dialogflow_v2/services/contexts/async_client.py +++ b/google/cloud/dialogflow_v2/services/contexts/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.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -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 from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport from .client import ContextsClient @@ -49,25 +46,20 @@ class ContextsAsyncClient: context_path = staticmethod(ContextsClient.context_path) parse_context_path = staticmethod(ContextsClient.parse_context_path) - common_billing_account_path = staticmethod( ContextsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ContextsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ContextsClient.common_folder_path) parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) - common_organization_path = staticmethod(ContextsClient.common_organization_path) parse_common_organization_path = staticmethod( ContextsClient.parse_common_organization_path ) - common_project_path = staticmethod(ContextsClient.common_project_path) parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) - common_location_path = staticmethod(ContextsClient.common_location_path) parse_common_location_path = staticmethod(ContextsClient.parse_common_location_path) @@ -119,7 +111,7 @@ def transport(self) -> ContextsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ContextsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -156,7 +148,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ContextsClient( credentials=credentials, transport=transport, @@ -191,7 +182,6 @@ async def list_contexts( 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. @@ -221,7 +211,6 @@ async def list_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -278,7 +267,6 @@ async def get_context( 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. @@ -322,7 +310,6 @@ async def get_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -380,7 +367,6 @@ async def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +410,6 @@ async def create_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -455,7 +440,7 @@ async def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = 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]] = (), @@ -478,7 +463,6 @@ async def update_context( 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 +506,6 @@ async def update_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -577,7 +560,6 @@ async def delete_context( 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. @@ -598,7 +580,6 @@ async def delete_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -648,7 +629,6 @@ async def delete_all_contexts( 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. @@ -669,7 +649,6 @@ async def delete_all_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/contexts/client.py b/google/cloud/dialogflow_v2/services/contexts/client.py index 6e32eab42..ae334ea51 100644 --- a/google/cloud/dialogflow_v2/services/contexts/client.py +++ b/google/cloud/dialogflow_v2/services/contexts/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.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -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 from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ContextsGrpcTransport from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport @@ -234,7 +231,7 @@ 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, ContextsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -371,7 +368,6 @@ def list_contexts( 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 +399,8 @@ def list_contexts( # there are no flattened fields. if not isinstance(request, context.ListContextsRequest): request = context.ListContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -459,7 +453,6 @@ def get_context( 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. @@ -505,10 +498,8 @@ def get_context( # there are no flattened fields. if not isinstance(request, context.GetContextRequest): request = context.GetContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -562,7 +553,6 @@ def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -608,10 +598,8 @@ def create_context( # there are no flattened fields. if not isinstance(request, gcd_context.CreateContextRequest): request = gcd_context.CreateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -638,7 +626,7 @@ def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = 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]] = (), @@ -661,7 +649,6 @@ def update_context( 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. @@ -707,10 +694,8 @@ def update_context( # there are no flattened fields. if not isinstance(request, gcd_context.UpdateContextRequest): request = gcd_context.UpdateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -761,7 +746,6 @@ def delete_context( 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. @@ -784,10 +768,8 @@ def delete_context( # there are no flattened fields. if not isinstance(request, context.DeleteContextRequest): request = context.DeleteContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -833,7 +815,6 @@ def delete_all_contexts( 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. @@ -856,10 +837,8 @@ def delete_all_contexts( # there are no flattened fields. if not isinstance(request, context.DeleteAllContextsRequest): request = context.DeleteAllContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/contexts/pagers.py b/google/cloud/dialogflow_v2/services/contexts/pagers.py index 90adad946..95b7f0374 100644 --- a/google/cloud/dialogflow_v2/services/contexts/pagers.py +++ b/google/cloud/dialogflow_v2/services/contexts/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, diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py b/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py index 7437034e4..d25eca3aa 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/contexts/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/dialogflow_v2/services/contexts/transports/base.py b/google/cloud/dialogflow_v2/services/contexts/transports/base.py index 350f2d7fc..07249b99d 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2/services/contexts/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.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -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 ContextsTransport(abc.ABC): """Abstract transport class for Contexts.""" @@ -48,21 +58,24 @@ class ContextsTransport(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,7 +84,7 @@ 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): @@ -85,29 +98,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -134,56 +194,53 @@ def _prep_wrapped_messages(self, client_info): @property def list_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.ListContextsRequest], - typing.Union[ - context.ListContextsResponse, typing.Awaitable[context.ListContextsResponse] - ], + Union[context.ListContextsResponse, Awaitable[context.ListContextsResponse]], ]: raise NotImplementedError() @property def get_context( self, - ) -> typing.Callable[ - [context.GetContextRequest], - typing.Union[context.Context, typing.Awaitable[context.Context]], + ) -> Callable[ + [context.GetContextRequest], Union[context.Context, Awaitable[context.Context]] ]: raise NotImplementedError() @property def create_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.CreateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def update_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.UpdateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def delete_context( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteContextRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def delete_all_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteAllContextsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py index 7e3153ef0..60884118a 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/contexts/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.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) @@ -329,7 +329,9 @@ def update_context( return self._stubs["update_context"] @property - def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty]: + def delete_context( + self, + ) -> Callable[[context.DeleteContextRequest], empty_pb2.Empty]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -348,14 +350,14 @@ def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], empty.Empty]: + ) -> Callable[[context.DeleteAllContextsRequest], empty_pb2.Empty]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -374,7 +376,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py index 3e5d003b5..a00089966 100644 --- a/google/cloud/dialogflow_v2/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/contexts/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.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO from .grpc import ContextsGrpcTransport @@ -55,7 +52,7 @@ class ContextsGrpcAsyncIOTransport(ContextsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -339,7 +338,7 @@ def update_context( @property def delete_context( self, - ) -> Callable[[context.DeleteContextRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteContextRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -358,14 +357,14 @@ def delete_context( self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -384,7 +383,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py b/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py index 9ab8de0b8..c0cb1cd03 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/__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 ConversationProfilesClient from .async_client import ConversationProfilesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py b/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py index e66165698..314e28898 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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.dialogflow_v2.services.conversation_profiles import pagers @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport from .client import ConversationProfilesClient @@ -54,6 +51,12 @@ class ConversationProfilesAsyncClient: agent_path = staticmethod(ConversationProfilesClient.agent_path) parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod( + ConversationProfilesClient.conversation_model_path + ) + parse_conversation_model_path = staticmethod( + ConversationProfilesClient.parse_conversation_model_path + ) conversation_profile_path = staticmethod( ConversationProfilesClient.conversation_profile_path ) @@ -66,31 +69,26 @@ class ConversationProfilesAsyncClient: parse_knowledge_base_path = staticmethod( ConversationProfilesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( ConversationProfilesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationProfilesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationProfilesClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationProfilesClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationProfilesClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationProfilesClient.common_project_path) parse_common_project_path = staticmethod( ConversationProfilesClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationProfilesClient.common_location_path) parse_common_location_path = staticmethod( ConversationProfilesClient.parse_common_location_path @@ -145,7 +143,7 @@ def transport(self) -> ConversationProfilesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -182,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationProfilesClient( credentials=credentials, transport=transport, @@ -214,7 +211,6 @@ async def list_conversation_profiles( 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. @@ -244,7 +240,6 @@ async def list_conversation_profiles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -297,7 +292,6 @@ async def get_conversation_profile( 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. @@ -324,7 +318,6 @@ async def get_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -385,7 +378,6 @@ async def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,7 +404,6 @@ async def create_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -443,7 +434,7 @@ async def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = 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 +465,6 @@ async def update_conversation_profile( 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. @@ -501,7 +491,6 @@ async def update_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -554,7 +543,6 @@ async def delete_conversation_profile( 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. @@ -575,7 +563,6 @@ async def delete_conversation_profile( # 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/dialogflow_v2/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2/services/conversation_profiles/client.py index 4f0495e3e..9b83cccd9 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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,9 +36,8 @@ from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationProfilesGrpcTransport from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport @@ -176,6 +173,24 @@ def parse_agent_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/agent$", path) return m.groupdict() if m else {} + @staticmethod + def conversation_model_path( + project: str, location: str, conversation_model: str, + ) -> str: + """Return a fully-qualified conversation_model string.""" + return "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + + @staticmethod + def parse_conversation_model_path(path: str) -> Dict[str, str]: + """Parse a conversation_model path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/conversationModels/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def conversation_profile_path(project: str, conversation_profile: str,) -> str: """Return a fully-qualified conversation_profile string.""" @@ -285,7 +300,7 @@ 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, ConversationProfilesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -419,7 +434,6 @@ def list_conversation_profiles( 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. @@ -453,10 +467,8 @@ def list_conversation_profiles( request, conversation_profile.ListConversationProfilesRequest ): request = conversation_profile.ListConversationProfilesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -507,7 +519,6 @@ def get_conversation_profile( 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. @@ -536,10 +547,8 @@ def get_conversation_profile( # there are no flattened fields. if not isinstance(request, conversation_profile.GetConversationProfileRequest): request = conversation_profile.GetConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -596,7 +605,6 @@ def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +635,8 @@ def create_conversation_profile( request, gcd_conversation_profile.CreateConversationProfileRequest ): request = gcd_conversation_profile.CreateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -659,7 +665,7 @@ def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = 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]] = (), @@ -690,7 +696,6 @@ def update_conversation_profile( 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 +726,8 @@ def update_conversation_profile( request, gcd_conversation_profile.UpdateConversationProfileRequest ): request = gcd_conversation_profile.UpdateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -775,7 +778,6 @@ def delete_conversation_profile( 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. @@ -800,10 +802,8 @@ def delete_conversation_profile( request, conversation_profile.DeleteConversationProfileRequest ): request = conversation_profile.DeleteConversationProfileRequest(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/dialogflow_v2/services/conversation_profiles/pagers.py b/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py index 0e261b842..672b07000 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/pagers.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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, diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py index e97774bcf..f2a4e2203 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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/dialogflow_v2/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py index 5768948c2..affb92d5e 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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.dialogflow_v2.types import conversation_profile from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport(abc.ABC): """Abstract transport class for ConversationProfiles.""" @@ -50,21 +60,24 @@ class ConversationProfilesTransport(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,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_conversation_profiles( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.ListConversationProfilesRequest], - typing.Union[ + Union[ conversation_profile.ListConversationProfilesResponse, - typing.Awaitable[conversation_profile.ListConversationProfilesResponse], + Awaitable[conversation_profile.ListConversationProfilesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_conversation_profiles( @property def get_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.GetConversationProfileRequest], - typing.Union[ + Union[ conversation_profile.ConversationProfile, - typing.Awaitable[conversation_profile.ConversationProfile], + Awaitable[conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_conversation_profile( @property def create_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.CreateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_conversation_profile( @property def update_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.UpdateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.DeleteConversationProfileRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py index 9af6dd273..581dfa3bc 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, 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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -358,7 +358,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> Callable[[conversation_profile.DeleteConversationProfileRequest], empty.Empty]: + ) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete conversation profile method over gRPC. Deletes the specified conversation profile. @@ -377,7 +379,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py index d6ec1c60c..f9493a17a 100644 --- a/google/cloud/dialogflow_v2/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversation_profiles/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.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationProfilesGrpcTransport @@ -58,7 +55,7 @@ class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): 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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -363,7 +362,8 @@ def update_conversation_profile( def delete_conversation_profile( self, ) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], Awaitable[empty.Empty] + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete conversation profile method over gRPC. @@ -383,7 +383,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2/services/conversations/__init__.py b/google/cloud/dialogflow_v2/services/conversations/__init__.py index cce809abe..f6f6b90ff 100644 --- a/google/cloud/dialogflow_v2/services/conversations/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversations/__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 ConversationsClient from .async_client import ConversationsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/conversations/async_client.py b/google/cloud/dialogflow_v2/services/conversations/async_client.py index 7afd626e5..094ab6419 100644 --- a/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2/services/conversations/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.dialogflow_v2.services.conversations import pagers from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport from .client import ConversationsClient @@ -59,31 +56,26 @@ class ConversationsAsyncClient: ) message_path = staticmethod(ConversationsClient.message_path) parse_message_path = staticmethod(ConversationsClient.parse_message_path) - common_billing_account_path = staticmethod( ConversationsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationsClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationsClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationsClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationsClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationsClient.common_project_path) parse_common_project_path = staticmethod( ConversationsClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationsClient.common_location_path) parse_common_location_path = staticmethod( ConversationsClient.parse_common_location_path @@ -137,7 +129,7 @@ def transport(self) -> ConversationsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -174,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationsClient( credentials=credentials, transport=transport, @@ -231,7 +222,6 @@ async def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -263,7 +253,6 @@ async def create_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -313,7 +302,6 @@ async def list_conversations( 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. @@ -343,7 +331,6 @@ async def list_conversations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -395,7 +382,6 @@ async def get_conversation( 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. @@ -427,7 +413,6 @@ async def get_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -476,7 +461,6 @@ async def complete_conversation( 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. @@ -508,7 +492,6 @@ async def complete_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -559,7 +542,6 @@ async def list_messages( 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. @@ -589,7 +571,6 @@ async def list_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/conversations/client.py b/google/cloud/dialogflow_v2/services/conversations/client.py index 16e68f100..087dbce8a 100644 --- a/google/cloud/dialogflow_v2/services/conversations/client.py +++ b/google/cloud/dialogflow_v2/services/conversations/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.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationsGrpcTransport from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport @@ -267,7 +264,7 @@ 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, ConversationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -426,7 +423,6 @@ def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -460,10 +456,8 @@ def create_conversation( # there are no flattened fields. if not isinstance(request, gcd_conversation.CreateConversationRequest): request = gcd_conversation.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -509,7 +503,6 @@ def list_conversations( 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. @@ -541,10 +534,8 @@ def list_conversations( # there are no flattened fields. if not isinstance(request, conversation.ListConversationsRequest): request = conversation.ListConversationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -592,7 +583,6 @@ def get_conversation( 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. @@ -626,10 +616,8 @@ def get_conversation( # there are no flattened fields. if not isinstance(request, conversation.GetConversationRequest): request = conversation.GetConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -674,7 +662,6 @@ def complete_conversation( 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. @@ -708,10 +695,8 @@ def complete_conversation( # there are no flattened fields. if not isinstance(request, conversation.CompleteConversationRequest): request = conversation.CompleteConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -758,7 +743,6 @@ def list_messages( 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. @@ -790,10 +774,8 @@ def list_messages( # there are no flattened fields. if not isinstance(request, conversation.ListMessagesRequest): request = conversation.ListMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/conversations/pagers.py b/google/cloud/dialogflow_v2/services/conversations/pagers.py index d770c7e8a..a833e5500 100644 --- a/google/cloud/dialogflow_v2/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2/services/conversations/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, diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py b/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py index 6597b6d01..2989914f7 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/conversations/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/dialogflow_v2/services/conversations/transports/base.py b/google/cloud/dialogflow_v2/services/conversations/transports/base.py index b96d45a4e..81b0c5a38 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2/services/conversations/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.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 ConversationsTransport(abc.ABC): """Abstract transport class for Conversations.""" @@ -47,21 +57,24 @@ class ConversationsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -132,23 +192,20 @@ def _prep_wrapped_messages(self, client_info): @property def create_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation.CreateConversationRequest], - typing.Union[ - gcd_conversation.Conversation, - typing.Awaitable[gcd_conversation.Conversation], - ], + Union[gcd_conversation.Conversation, Awaitable[gcd_conversation.Conversation]], ]: raise NotImplementedError() @property def list_conversations( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListConversationsRequest], - typing.Union[ + Union[ conversation.ListConversationsResponse, - typing.Awaitable[conversation.ListConversationsResponse], + Awaitable[conversation.ListConversationsResponse], ], ]: raise NotImplementedError() @@ -156,33 +213,29 @@ def list_conversations( @property def get_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.GetConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def complete_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.CompleteConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def list_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListMessagesRequest], - typing.Union[ + Union[ conversation.ListMessagesResponse, - typing.Awaitable[conversation.ListMessagesResponse], + Awaitable[conversation.ListMessagesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py index f3b8a5578..c7cf35d07 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/conversations/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,21 +13,19 @@ # 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.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - from .base import ConversationsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) diff --git a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py index 480cdcfae..947afd762 100644 --- a/google/cloud/dialogflow_v2/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/conversations/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,22 +13,20 @@ # 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.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -55,7 +52,7 @@ class ConversationsGrpcAsyncIOTransport(ConversationsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/documents/__init__.py b/google/cloud/dialogflow_v2/services/documents/__init__.py index 5f6db6815..f610c36b0 100644 --- a/google/cloud/dialogflow_v2/services/documents/__init__.py +++ b/google/cloud/dialogflow_v2/services/documents/__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 DocumentsClient from .async_client import DocumentsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/documents/async_client.py b/google/cloud/dialogflow_v2/services/documents/async_client.py index 62632ef32..4b7427198 100644 --- a/google/cloud/dialogflow_v2/services/documents/async_client.py +++ b/google/cloud/dialogflow_v2/services/documents/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.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport from .client import DocumentsClient @@ -53,25 +50,20 @@ class DocumentsAsyncClient: document_path = staticmethod(DocumentsClient.document_path) parse_document_path = staticmethod(DocumentsClient.parse_document_path) - common_billing_account_path = staticmethod( DocumentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( DocumentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DocumentsClient.common_folder_path) parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentsClient.common_organization_path) parse_common_organization_path = staticmethod( DocumentsClient.parse_common_organization_path ) - common_project_path = staticmethod(DocumentsClient.common_project_path) parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) - common_location_path = staticmethod(DocumentsClient.common_location_path) parse_common_location_path = staticmethod( DocumentsClient.parse_common_location_path @@ -125,7 +117,7 @@ def transport(self) -> DocumentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DocumentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -162,7 +154,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DocumentsClient( credentials=credentials, transport=transport, @@ -194,7 +185,6 @@ async def list_documents( 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. @@ -224,7 +214,6 @@ async def list_documents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -276,7 +265,6 @@ async def get_document( 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 +298,6 @@ async def get_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -367,7 +354,6 @@ async def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -405,7 +391,6 @@ async def create_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -465,7 +450,6 @@ async def delete_document( 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. @@ -505,7 +489,6 @@ async def delete_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -530,7 +513,7 @@ async def delete_document( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -542,7 +525,7 @@ async def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = 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]] = (), @@ -570,7 +553,6 @@ async def update_document( 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. @@ -608,7 +590,6 @@ async def update_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -688,7 +669,6 @@ async def reload_document( This corresponds to the ``content_uri`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -726,7 +706,6 @@ async def reload_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if content_uri is not None: diff --git a/google/cloud/dialogflow_v2/services/documents/client.py b/google/cloud/dialogflow_v2/services/documents/client.py index 3863502ed..b6f9efc9f 100644 --- a/google/cloud/dialogflow_v2/services/documents/client.py +++ b/google/cloud/dialogflow_v2/services/documents/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.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DocumentsGrpcTransport from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport @@ -238,7 +235,7 @@ 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, DocumentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -372,7 +369,6 @@ def list_documents( 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. @@ -404,10 +400,8 @@ def list_documents( # there are no flattened fields. if not isinstance(request, document.ListDocumentsRequest): request = document.ListDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -455,7 +449,6 @@ def get_document( 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 +484,8 @@ def get_document( # there are no flattened fields. if not isinstance(request, document.GetDocumentRequest): request = document.GetDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -547,7 +538,6 @@ def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -587,10 +577,8 @@ def create_document( # there are no flattened fields. if not isinstance(request, gcd_document.CreateDocumentRequest): request = gcd_document.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -646,7 +634,6 @@ def delete_document( 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. @@ -688,10 +675,8 @@ def delete_document( # there are no flattened fields. if not isinstance(request, document.DeleteDocumentRequest): request = document.DeleteDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -712,7 +697,7 @@ def delete_document( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -724,7 +709,7 @@ def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = 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]] = (), @@ -752,7 +737,6 @@ def update_document( 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. @@ -792,10 +776,8 @@ def update_document( # there are no flattened fields. if not isinstance(request, gcd_document.UpdateDocumentRequest): request = gcd_document.UpdateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -871,7 +853,6 @@ def reload_document( This corresponds to the ``content_uri`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +892,8 @@ def reload_document( # there are no flattened fields. if not isinstance(request, document.ReloadDocumentRequest): request = document.ReloadDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if content_uri is not None: diff --git a/google/cloud/dialogflow_v2/services/documents/pagers.py b/google/cloud/dialogflow_v2/services/documents/pagers.py index 9c5ec068a..073814d75 100644 --- a/google/cloud/dialogflow_v2/services/documents/pagers.py +++ b/google/cloud/dialogflow_v2/services/documents/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, diff --git a/google/cloud/dialogflow_v2/services/documents/transports/__init__.py b/google/cloud/dialogflow_v2/services/documents/transports/__init__.py index af02ba19c..5d4948aa0 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/documents/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/dialogflow_v2/services/documents/transports/base.py b/google/cloud/dialogflow_v2/services/documents/transports/base.py index 39425610b..20350ece5 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2/services/documents/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,22 +13,22 @@ # 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.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,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 DocumentsTransport(abc.ABC): """Abstract transport class for Documents.""" @@ -49,21 +59,24 @@ class DocumentsTransport(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 @@ -72,7 +85,7 @@ 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): @@ -86,29 +99,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -140,11 +200,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ListDocumentsRequest], - typing.Union[ - document.ListDocumentsResponse, - typing.Awaitable[document.ListDocumentsResponse], + Union[ + document.ListDocumentsResponse, Awaitable[document.ListDocumentsResponse] ], ]: raise NotImplementedError() @@ -152,45 +211,45 @@ def list_documents( @property def get_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.GetDocumentRequest], - typing.Union[document.Document, typing.Awaitable[document.Document]], + Union[document.Document, Awaitable[document.Document]], ]: raise NotImplementedError() @property def create_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.CreateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.DeleteDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.UpdateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def reload_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ReloadDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc.py index e5cb89e6a..5a11c51e9 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/documents/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,23 +13,21 @@ # 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.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, 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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -296,7 +296,7 @@ def get_document( @property def create_document( self, - ) -> Callable[[gcd_document.CreateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.CreateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the create document method over gRPC. Creates a new document. @@ -319,14 +319,14 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], operations.Operation]: + ) -> Callable[[document.DeleteDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -349,14 +349,14 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @property def update_document( self, - ) -> Callable[[gcd_document.UpdateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.UpdateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the update document method over gRPC. Updates the specified document. @@ -379,14 +379,14 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], operations.Operation]: + ) -> Callable[[document.ReloadDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -416,7 +416,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py index 105dd3739..e2173a7af 100644 --- a/google/cloud/dialogflow_v2/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/documents/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,24 +13,22 @@ # 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.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO from .grpc import DocumentsGrpcTransport @@ -57,7 +54,7 @@ class DocumentsGrpcAsyncIOTransport(DocumentsTransport): 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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -305,7 +304,7 @@ def get_document( def create_document( self, ) -> Callable[ - [gcd_document.CreateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.CreateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create document method over gRPC. @@ -329,14 +328,16 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.DeleteDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -359,7 +360,7 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @@ -367,7 +368,7 @@ def delete_document( def update_document( self, ) -> Callable[ - [gcd_document.UpdateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.UpdateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update document method over gRPC. @@ -391,14 +392,16 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ReloadDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -428,7 +431,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2/services/entity_types/__init__.py b/google/cloud/dialogflow_v2/services/entity_types/__init__.py index f52849c66..77cd53e9c 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/entity_types/async_client.py b/google/cloud/dialogflow_v2/services/entity_types/async_client.py index a3c67d500..52e5650cc 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/async_client.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -53,27 +50,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 @@ -127,7 +119,7 @@ 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, @@ -164,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -206,7 +197,6 @@ async def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +226,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 if language_code is not None: @@ -301,7 +290,6 @@ async def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -341,7 +329,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 if language_code is not None: @@ -406,7 +393,6 @@ async def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -446,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: @@ -505,7 +490,6 @@ async def update_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +529,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 language_code is not None: @@ -595,7 +578,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. @@ -616,7 +598,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 @@ -656,7 +637,6 @@ async def batch_update_entity_types( request (:class:`google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest`): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -674,7 +654,6 @@ async def batch_update_entity_types( """ # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -699,7 +678,7 @@ async def batch_update_entity_types( response, self._client._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -738,7 +717,6 @@ async def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -778,10 +756,8 @@ async def batch_delete_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if entity_type_names: request.entity_type_names.extend(entity_type_names) @@ -806,8 +782,8 @@ async def batch_delete_entity_types( 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. @@ -856,7 +832,6 @@ async def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -896,12 +871,10 @@ async def batch_create_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -926,8 +899,8 @@ async def batch_create_entities( 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. @@ -980,7 +953,6 @@ async def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1020,12 +992,10 @@ async def batch_update_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -1050,8 +1020,8 @@ async def batch_update_entities( 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. @@ -1103,7 +1073,6 @@ async def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1143,12 +1112,10 @@ async def batch_delete_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entity_values: request.entity_values.extend(entity_values) @@ -1173,8 +1140,8 @@ async def batch_delete_entities( 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/dialogflow_v2/services/entity_types/client.py b/google/cloud/dialogflow_v2/services/entity_types/client.py index 497f8a433..25cedc2d6 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/client.py +++ b/google/cloud/dialogflow_v2/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 @@ -37,9 +35,8 @@ from google.cloud.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from .transports.base import EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -237,7 +234,7 @@ 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, @@ -381,7 +378,6 @@ def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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,10 +409,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 if language_code is not None: @@ -477,7 +471,6 @@ def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +512,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 if language_code is not None: @@ -583,7 +574,6 @@ def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +615,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): request = gcd_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: @@ -683,7 +671,6 @@ def update_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -725,10 +712,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): request = gcd_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 language_code is not None: @@ -774,7 +759,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. @@ -797,10 +781,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 @@ -836,7 +818,6 @@ def batch_update_entity_types( request (google.cloud.dialogflow_v2.types.BatchUpdateEntityTypesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -854,7 +835,6 @@ def batch_update_entity_types( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a entity_type.BatchUpdateEntityTypesRequest. # There's no risk of modifying the input as we've already verified @@ -882,7 +862,7 @@ def batch_update_entity_types( response, self._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -921,7 +901,6 @@ def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -963,10 +942,8 @@ def batch_delete_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): request = entity_type.BatchDeleteEntityTypesRequest(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_names is not None: @@ -991,8 +968,8 @@ def batch_delete_entity_types( 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. @@ -1041,7 +1018,6 @@ def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1083,10 +1059,8 @@ def batch_create_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchCreateEntitiesRequest): request = entity_type.BatchCreateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1111,8 +1085,8 @@ def batch_create_entities( 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. @@ -1165,7 +1139,6 @@ def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1207,10 +1180,8 @@ def batch_update_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): request = entity_type.BatchUpdateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1235,8 +1206,8 @@ def batch_update_entities( 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. @@ -1288,7 +1259,6 @@ def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1330,10 +1300,8 @@ def batch_delete_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): request = entity_type.BatchDeleteEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_values is not None: @@ -1358,8 +1326,8 @@ def batch_delete_entities( 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/dialogflow_v2/services/entity_types/pagers.py b/google/cloud/dialogflow_v2/services/entity_types/pagers.py index 12d4aa9ed..c00d1f55b 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/pagers.py +++ b/google/cloud/dialogflow_v2/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, diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py b/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py index 963959d1a..07ea82e1b 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/entity_types/transports/base.py index a2b32c6a1..ed8892ca7 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -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 EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -50,21 +60,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 @@ -73,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -163,11 +223,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @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() @@ -175,85 +235,81 @@ 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[ [gcd_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_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() @property def batch_update_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_create_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchCreateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_update_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py index cf9544f77..c486c108d 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -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 EntityTypesTransport, 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 @@ -180,7 +178,7 @@ def __init__( 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,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, ) @@ -355,7 +355,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. @@ -374,14 +374,16 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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"] @property def batch_update_entity_types( self, - ) -> Callable[[entity_type.BatchUpdateEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch update entity types method over gRPC. Updates/Creates multiple entity types in the specified agent. @@ -403,14 +405,16 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @property def batch_delete_entity_types( self, - ) -> Callable[[entity_type.BatchDeleteEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch delete entity types method over gRPC. Deletes entity types in the specified agent. @@ -432,14 +436,14 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @property def batch_create_entities( self, - ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch create entities method over gRPC. Creates multiple new entities in the specified entity type. @@ -461,14 +465,14 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @property def batch_update_entities( self, - ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch update entities method over gRPC. Updates or creates multiple entities in the specified entity @@ -492,14 +496,14 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @property def batch_delete_entities( self, - ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete entities method over gRPC. Deletes entities in the specified entity type. @@ -521,7 +525,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py index 7ce05d2e1..35b60cea1 100644 --- a/google/cloud/dialogflow_v2/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type -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 EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -58,7 +55,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, @@ -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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -364,7 +363,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. @@ -383,7 +382,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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"] @@ -391,7 +390,7 @@ def delete_entity_type( def batch_update_entity_types( self, ) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entity types method over gRPC. @@ -414,7 +413,7 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @@ -422,7 +421,7 @@ def batch_update_entity_types( def batch_delete_entity_types( self, ) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entity types method over gRPC. @@ -445,7 +444,7 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @@ -453,7 +452,7 @@ def batch_delete_entity_types( def batch_create_entities( self, ) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchCreateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch create entities method over gRPC. @@ -476,7 +475,7 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @@ -484,7 +483,7 @@ def batch_create_entities( def batch_update_entities( self, ) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entities method over gRPC. @@ -509,7 +508,7 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @@ -517,7 +516,7 @@ def batch_update_entities( def batch_delete_entities( self, ) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entities method over gRPC. @@ -540,7 +539,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2/services/environments/__init__.py b/google/cloud/dialogflow_v2/services/environments/__init__.py index a67f2316d..0c2be9484 100644 --- a/google/cloud/dialogflow_v2/services/environments/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/environments/async_client.py b/google/cloud/dialogflow_v2/services/environments/async_client.py index acd916032..c09e92cbc 100644 --- a/google/cloud/dialogflow_v2/services/environments/async_client.py +++ b/google/cloud/dialogflow_v2/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,15 +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.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.types import environment - +from google.cloud.dialogflow_v2.types import fulfillment +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 @@ -48,27 +47,24 @@ class EnvironmentsAsyncClient: environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_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 @@ -122,7 +118,7 @@ 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, @@ -159,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -171,6 +166,7 @@ async def list_environments( self, request: environment.ListEnvironmentsRequest = None, *, + parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -182,7 +178,16 @@ async def list_environments( request (:class:`google.cloud.dialogflow_v2.types.ListEnvironmentsRequest`): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (:class:`str`): + Required. The agent to list all environments from. + Format: + - ``projects//agent`` + - ``projects//locations//agent`` + + 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. @@ -199,9 +204,22 @@ async def list_environments( """ # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = environment.ListEnvironmentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( @@ -228,6 +246,324 @@ async def list_environments( # Done; return the response. return response + async def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(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.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(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.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(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.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(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.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + 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.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(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.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2/services/environments/client.py b/google/cloud/dialogflow_v2/services/environments/client.py index d54531fe3..4752bfe52 100644 --- a/google/cloud/dialogflow_v2/services/environments/client.py +++ b/google/cloud/dialogflow_v2/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 @@ -34,7 +32,8 @@ from google.cloud.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.types import environment - +from google.cloud.dialogflow_v2.types import fulfillment +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 @@ -170,6 +169,17 @@ def parse_environment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def fulfillment_path(project: str,) -> str: + """Return a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project,) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str, str]: + """Parse a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" @@ -232,7 +242,7 @@ 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, @@ -346,6 +356,7 @@ def list_environments( self, request: environment.ListEnvironmentsRequest = None, *, + parent: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -357,7 +368,16 @@ def list_environments( request (google.cloud.dialogflow_v2.types.ListEnvironmentsRequest): The request object. The request message for [Environments.ListEnvironments][google.cloud.dialogflow.v2.Environments.ListEnvironments]. + parent (str): + Required. The agent to list all environments from. + Format: + + - ``projects//agent`` + - ``projects//locations//agent`` + 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. @@ -374,6 +394,14 @@ def list_environments( """ # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a environment.ListEnvironmentsRequest. @@ -381,6 +409,10 @@ 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 # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -404,6 +436,329 @@ def list_environments( # Done; return the response. return response + def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + 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.dialogflow_v2.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + 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.dialogflow_v2.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2/services/environments/pagers.py b/google/cloud/dialogflow_v2/services/environments/pagers.py index ea6aa5567..7dd905368 100644 --- a/google/cloud/dialogflow_v2/services/environments/pagers.py +++ b/google/cloud/dialogflow_v2/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, @@ -155,3 +153,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2/services/environments/transports/__init__.py b/google/cloud/dialogflow_v2/services/environments/transports/__init__.py index aff44bcdd..c72efee48 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/environments/transports/base.py b/google/cloud/dialogflow_v2/services/environments/transports/base.py index 35fd89eb7..beb636a3d 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2/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,19 +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.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +37,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.""" @@ -46,21 +57,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 @@ -69,7 +83,7 @@ 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): @@ -83,45 +97,156 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { self.list_environments: gapic_v1.method.wrap_method( self.list_environments, default_timeout=None, client_info=client_info, ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, default_timeout=None, client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, default_timeout=None, client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, default_timeout=None, client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, default_timeout=None, client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), } @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def delete_environment( + self, + ) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, Awaitable[environment.EnvironmentHistory] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc.py index fd702da8b..ca713c98d 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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,20 +13,19 @@ # 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.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -51,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, @@ -65,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 @@ -175,7 +174,7 @@ def __init__( 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, @@ -206,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, ) @@ -251,5 +252,149 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[[environment.GetEnvironmentRequest], environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + 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_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[[environment.CreateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[[environment.UpdateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], environment.EnvironmentHistory + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + 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_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py index f6c738c97..93f066c99 100644 --- a/google/cloud/dialogflow_v2/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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,21 +13,20 @@ # 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.dialogflow_v2.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -54,7 +52,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, @@ -81,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, ) @@ -95,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, @@ -109,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 @@ -167,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -256,5 +256,156 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + 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_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory], + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + 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_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/__init__.py b/google/cloud/dialogflow_v2/services/fulfillments/__init__.py new file mode 100644 index 000000000..6bade52dd --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + "FulfillmentsClient", + "FulfillmentsAsyncClient", +) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/async_client.py b/google/cloud/dialogflow_v2/services/fulfillments/async_client.py new file mode 100644 index 000000000..9ba55d46e --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/async_client.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod( + FulfillmentsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + FulfillmentsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod( + FulfillmentsClient.parse_common_organization_path + ) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod( + FulfillmentsClient.parse_common_project_path + ) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod( + FulfillmentsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Return the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the fulfillments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FulfillmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FulfillmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetFulfillmentRequest`): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + 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.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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 = fulfillment.GetFulfillmentRequest(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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest`): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_fulfillment, + 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( + (("fulfillment.name", request.fulfillment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FulfillmentsAsyncClient",) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/client.py b/google/cloud/dialogflow_v2/services/fulfillments/client.py new file mode 100644 index 000000000..e8fbdb99e --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/client.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[FulfillmentsTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class FulfillmentsClient(metaclass=FulfillmentsClientMeta): + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Return the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Return a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project,) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str, str]: + """Parse a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the fulfillments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FulfillmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (google.cloud.dialogflow_v2.types.GetFulfillmentRequest): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + + 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.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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 fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(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_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateFulfillmentRequest): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("fulfillment.name", request.fulfillment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FulfillmentsClient",) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py new file mode 100644 index 000000000..d822b662b --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry["grpc"] = FulfillmentsGrpcTransport +_transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + "FulfillmentsTransport", + "FulfillmentsGrpcTransport", + "FulfillmentsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py new file mode 100644 index 000000000..750cc4860 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/base.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # 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. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, default_timeout=None, client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, default_timeout=None, client_info=client_info, + ), + } + + @property + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[fulfillment.Fulfillment, Awaitable[fulfillment.Fulfillment]], + ]: + raise NotImplementedError() + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[gcd_fulfillment.Fulfillment, Awaitable[gcd_fulfillment.Fulfillment]], + ]: + raise NotImplementedError() + + +__all__ = ("FulfillmentsTransport",) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py new file mode 100644 index 000000000..8eb7fd8f7 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment( + self, + ) -> Callable[[fulfillment.GetFulfillmentRequest], fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + 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_fulfillment" not in self._stubs: + self._stubs["get_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment", + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs["get_fulfillment"] + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], gcd_fulfillment.Fulfillment + ]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fulfillment" not in self._stubs: + self._stubs["update_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment", + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs["update_fulfillment"] + + +__all__ = ("FulfillmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py new file mode 100644 index 000000000..b0f1afd0f --- /dev/null +++ b/google/cloud/dialogflow_v2/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + 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, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], Awaitable[fulfillment.Fulfillment] + ]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + 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_fulfillment" not in self._stubs: + self._stubs["get_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Fulfillments/GetFulfillment", + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs["get_fulfillment"] + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment], + ]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fulfillment" not in self._stubs: + self._stubs["update_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Fulfillments/UpdateFulfillment", + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs["update_fulfillment"] + + +__all__ = ("FulfillmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2/services/intents/__init__.py b/google/cloud/dialogflow_v2/services/intents/__init__.py index 8719a9b64..5a2c263cf 100644 --- a/google/cloud/dialogflow_v2/services/intents/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/intents/async_client.py b/google/cloud/dialogflow_v2/services/intents/async_client.py index 2d1ba2aa9..88ce890d3 100644 --- a/google/cloud/dialogflow_v2/services/intents/async_client.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -55,25 +52,20 @@ class IntentsAsyncClient: parse_context_path = staticmethod(IntentsClient.parse_context_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) @@ -125,7 +117,7 @@ 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, @@ -162,7 +154,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -204,7 +195,6 @@ async def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -234,7 +224,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 if language_code is not None: @@ -299,7 +288,6 @@ async def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -335,7 +323,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 if language_code is not None: @@ -400,7 +387,6 @@ async def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -436,7 +422,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: @@ -470,7 +455,7 @@ async def update_intent( *, intent: gcd_intent.Intent = None, language_code: str = 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]] = (), @@ -503,7 +488,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. @@ -539,7 +523,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 language_code is not None: @@ -594,7 +577,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. @@ -615,7 +597,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 @@ -682,7 +663,6 @@ async def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -713,7 +693,6 @@ async def batch_update_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -743,7 +722,7 @@ async def batch_update_intents( response, self._client._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -782,7 +761,6 @@ async def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +800,8 @@ async def batch_delete_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if intents: request.intents.extend(intents) @@ -850,8 +826,8 @@ async def batch_delete_intents( 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/dialogflow_v2/services/intents/client.py b/google/cloud/dialogflow_v2/services/intents/client.py index fd249f7fc..beeda1de2 100644 --- a/google/cloud/dialogflow_v2/services/intents/client.py +++ b/google/cloud/dialogflow_v2/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 @@ -38,10 +36,9 @@ from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -251,7 +248,7 @@ 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, @@ -395,7 +392,6 @@ def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -427,10 +423,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 if language_code is not None: @@ -491,7 +485,6 @@ def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -529,10 +522,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 if language_code is not None: @@ -593,7 +584,6 @@ def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -631,10 +621,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.CreateIntentRequest): request = gcd_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: @@ -664,7 +652,7 @@ def update_intent( *, intent: gcd_intent.Intent = None, language_code: str = 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]] = (), @@ -697,7 +685,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. @@ -735,10 +722,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.UpdateIntentRequest): request = gcd_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 language_code is not None: @@ -789,7 +774,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. @@ -812,10 +796,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 @@ -878,7 +860,6 @@ def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +892,8 @@ def batch_update_intents( # there are no flattened fields. if not isinstance(request, intent.BatchUpdateIntentsRequest): request = intent.BatchUpdateIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -940,7 +919,7 @@ def batch_update_intents( response, self._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -979,7 +958,6 @@ def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1021,10 +999,8 @@ def batch_delete_intents( # there are no flattened fields. if not isinstance(request, intent.BatchDeleteIntentsRequest): request = intent.BatchDeleteIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intents is not None: @@ -1047,8 +1023,8 @@ def batch_delete_intents( 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/dialogflow_v2/services/intents/pagers.py b/google/cloud/dialogflow_v2/services/intents/pagers.py index d19ace9a4..e896fb496 100644 --- a/google/cloud/dialogflow_v2/services/intents/pagers.py +++ b/google/cloud/dialogflow_v2/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, diff --git a/google/cloud/dialogflow_v2/services/intents/transports/__init__.py b/google/cloud/dialogflow_v2/services/intents/transports/__init__.py index 41fde33b5..974a58103 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/intents/transports/base.py b/google/cloud/dialogflow_v2/services/intents/transports/base.py index 57253e26f..31e64643a 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -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 IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -50,21 +60,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 @@ -73,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -148,65 +208,61 @@ def operations_client(self) -> operations_v1.OperationsClient: @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[ [gcd_intent.CreateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.UpdateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_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() @property def batch_update_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchUpdateIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchDeleteIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc.py index 605e3f42f..ce1c9d409 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -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 IntentsTransport, 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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -344,7 +344,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 and its direct or @@ -364,14 +364,14 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchUpdateIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -393,14 +393,14 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchDeleteIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -422,7 +422,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py index 4c2719a16..35838fa40 100644 --- a/google/cloud/dialogflow_v2/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -57,7 +54,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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -354,7 +353,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 and its direct or @@ -374,14 +373,16 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchUpdateIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -403,14 +404,16 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchDeleteIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -432,7 +435,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py b/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py index be24a37d1..24204c982 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/__init__.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/__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 KnowledgeBasesClient from .async_client import KnowledgeBasesAsyncClient diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py b/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py index 33d074e30..17cd680ad 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/async_client.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport from .client import KnowledgeBasesClient @@ -52,31 +49,26 @@ class KnowledgeBasesAsyncClient: parse_knowledge_base_path = staticmethod( KnowledgeBasesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( KnowledgeBasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( KnowledgeBasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) parse_common_folder_path = staticmethod( KnowledgeBasesClient.parse_common_folder_path ) - common_organization_path = staticmethod( KnowledgeBasesClient.common_organization_path ) parse_common_organization_path = staticmethod( KnowledgeBasesClient.parse_common_organization_path ) - common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) parse_common_project_path = staticmethod( KnowledgeBasesClient.parse_common_project_path ) - common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) parse_common_location_path = staticmethod( KnowledgeBasesClient.parse_common_location_path @@ -130,7 +122,7 @@ def transport(self) -> KnowledgeBasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -167,7 +159,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = KnowledgeBasesClient( credentials=credentials, transport=transport, @@ -199,7 +190,6 @@ async def list_knowledge_bases( 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. @@ -229,7 +219,6 @@ async def list_knowledge_bases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -282,7 +271,6 @@ async def get_knowledge_base( 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. @@ -319,7 +307,6 @@ async def get_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -374,7 +361,6 @@ async def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -411,7 +397,6 @@ async def create_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -460,7 +445,6 @@ async def delete_knowledge_base( 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. @@ -481,7 +465,6 @@ async def delete_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -509,7 +492,7 @@ async def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = 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]] = (), @@ -535,7 +518,6 @@ async def update_knowledge_base( 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. @@ -572,7 +554,6 @@ async def update_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/client.py b/google/cloud/dialogflow_v2/services/knowledge_bases/client.py index d5f171ef9..8b1ca0daf 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/client.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KnowledgeBasesGrpcTransport from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport @@ -236,7 +233,7 @@ 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, KnowledgeBasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -370,7 +367,6 @@ def list_knowledge_bases( 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. @@ -402,10 +398,8 @@ def list_knowledge_bases( # there are no flattened fields. if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): request = knowledge_base.ListKnowledgeBasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -454,7 +448,6 @@ def get_knowledge_base( 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. @@ -493,10 +486,8 @@ def get_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): request = knowledge_base.GetKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -547,7 +538,6 @@ def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -586,10 +576,8 @@ def create_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -634,7 +622,6 @@ def delete_knowledge_base( 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. @@ -657,10 +644,8 @@ def delete_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): request = knowledge_base.DeleteKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -684,7 +669,7 @@ def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = 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]] = (), @@ -710,7 +695,6 @@ def update_knowledge_base( 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. @@ -749,10 +733,8 @@ def update_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py b/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py index 6939025df..275d8ef25 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/pagers.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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, diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py index a3ac400b0..38da4326d 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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/dialogflow_v2/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py index 8173590b5..cb9322aca 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport(abc.ABC): """Abstract transport class for KnowledgeBases.""" @@ -48,21 +58,24 @@ class KnowledgeBasesTransport(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,7 +84,7 @@ 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): @@ -85,29 +98,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -139,11 +199,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_knowledge_bases( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.ListKnowledgeBasesRequest], - typing.Union[ + Union[ knowledge_base.ListKnowledgeBasesResponse, - typing.Awaitable[knowledge_base.ListKnowledgeBasesResponse], + Awaitable[knowledge_base.ListKnowledgeBasesResponse], ], ]: raise NotImplementedError() @@ -151,22 +211,20 @@ def list_knowledge_bases( @property def get_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.GetKnowledgeBaseRequest], - typing.Union[ - knowledge_base.KnowledgeBase, typing.Awaitable[knowledge_base.KnowledgeBase] - ], + Union[knowledge_base.KnowledgeBase, Awaitable[knowledge_base.KnowledgeBase]], ]: raise NotImplementedError() @property def create_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.CreateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() @@ -174,20 +232,20 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.DeleteKnowledgeBaseRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def update_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py index dd1f16ca4..3aa6b1f7c 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, 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 @@ -177,7 +175,7 @@ def __init__( 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, @@ -208,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, ) @@ -314,7 +314,7 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty.Empty]: + ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty_pb2.Empty]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -333,7 +333,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py index f8372de6a..5bc13c924 100644 --- a/google/cloud/dialogflow_v2/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/knowledge_bases/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.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .grpc import KnowledgeBasesGrpcTransport @@ -56,7 +53,7 @@ class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): 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, @@ -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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -319,7 +318,9 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -338,7 +339,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2/services/participants/__init__.py b/google/cloud/dialogflow_v2/services/participants/__init__.py index 9ebfb1f70..942327781 100644 --- a/google/cloud/dialogflow_v2/services/participants/__init__.py +++ b/google/cloud/dialogflow_v2/services/participants/__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 ParticipantsClient from .async_client import ParticipantsAsyncClient diff --git a/google/cloud/dialogflow_v2/services/participants/async_client.py b/google/cloud/dialogflow_v2/services/participants/async_client.py index beba5d8c1..c16491271 100644 --- a/google/cloud/dialogflow_v2/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2/services/participants/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.dialogflow_v2.services.participants import pagers from google.cloud.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant from google.cloud.dialogflow_v2.types import session -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 ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport from .client import ParticipantsClient @@ -61,27 +58,22 @@ class ParticipantsAsyncClient: parse_session_entity_type_path = staticmethod( ParticipantsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( ParticipantsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ParticipantsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ParticipantsClient.common_folder_path) parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) - common_organization_path = staticmethod(ParticipantsClient.common_organization_path) parse_common_organization_path = staticmethod( ParticipantsClient.parse_common_organization_path ) - common_project_path = staticmethod(ParticipantsClient.common_project_path) parse_common_project_path = staticmethod( ParticipantsClient.parse_common_project_path ) - common_location_path = staticmethod(ParticipantsClient.common_location_path) parse_common_location_path = staticmethod( ParticipantsClient.parse_common_location_path @@ -135,7 +127,7 @@ def transport(self) -> ParticipantsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ParticipantsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -172,7 +164,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ParticipantsClient( credentials=credentials, transport=transport, @@ -209,7 +200,6 @@ async def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +226,6 @@ async def create_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -284,7 +273,6 @@ async def get_participant( 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. @@ -311,7 +299,6 @@ async def get_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -359,7 +346,6 @@ async def list_participants( 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. @@ -389,7 +375,6 @@ async def list_participants( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -424,7 +409,7 @@ async def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = 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]] = (), @@ -447,7 +432,6 @@ async def update_participant( 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 +458,6 @@ async def update_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -544,7 +527,6 @@ async def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +553,6 @@ async def analyze_content( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -632,7 +613,6 @@ async def suggest_articles( 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. @@ -659,7 +639,6 @@ async def suggest_articles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -707,7 +686,6 @@ async def suggest_faq_answers( 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. @@ -734,7 +712,6 @@ async def suggest_faq_answers( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/participants/client.py b/google/cloud/dialogflow_v2/services/participants/client.py index 9500f818f..192ccc33f 100644 --- a/google/cloud/dialogflow_v2/services/participants/client.py +++ b/google/cloud/dialogflow_v2/services/participants/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.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant from google.cloud.dialogflow_v2.types import session -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 ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ParticipantsGrpcTransport from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport @@ -297,7 +294,7 @@ 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, ParticipantsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -436,7 +433,6 @@ def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -465,10 +461,8 @@ def create_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.CreateParticipantRequest): request = gcd_participant.CreateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -512,7 +506,6 @@ def get_participant( 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. @@ -541,10 +534,8 @@ def get_participant( # there are no flattened fields. if not isinstance(request, participant.GetParticipantRequest): request = participant.GetParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -588,7 +579,6 @@ def list_participants( 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. @@ -620,10 +610,8 @@ def list_participants( # there are no flattened fields. if not isinstance(request, participant.ListParticipantsRequest): request = participant.ListParticipantsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -654,7 +642,7 @@ def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = 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]] = (), @@ -677,7 +665,6 @@ def update_participant( 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. @@ -706,10 +693,8 @@ def update_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.UpdateParticipantRequest): request = gcd_participant.UpdateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -775,7 +760,6 @@ def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +788,8 @@ def analyze_content( # there are no flattened fields. if not isinstance(request, gcd_participant.AnalyzeContentRequest): request = gcd_participant.AnalyzeContentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -857,7 +839,6 @@ def suggest_articles( 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. @@ -886,10 +867,8 @@ def suggest_articles( # there are no flattened fields. if not isinstance(request, participant.SuggestArticlesRequest): request = participant.SuggestArticlesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -933,7 +912,6 @@ def suggest_faq_answers( 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. @@ -962,10 +940,8 @@ def suggest_faq_answers( # there are no flattened fields. if not isinstance(request, participant.SuggestFaqAnswersRequest): request = participant.SuggestFaqAnswersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2/services/participants/pagers.py b/google/cloud/dialogflow_v2/services/participants/pagers.py index 48ce3c8ac..6966dff39 100644 --- a/google/cloud/dialogflow_v2/services/participants/pagers.py +++ b/google/cloud/dialogflow_v2/services/participants/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, diff --git a/google/cloud/dialogflow_v2/services/participants/transports/__init__.py b/google/cloud/dialogflow_v2/services/participants/transports/__init__.py index 91a4cec1c..522813c1c 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/__init__.py +++ b/google/cloud/dialogflow_v2/services/participants/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/dialogflow_v2/services/participants/transports/base.py b/google/cloud/dialogflow_v2/services/participants/transports/base.py index 357674581..62cbe33a9 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2/services/participants/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.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 ParticipantsTransport(abc.ABC): """Abstract transport class for Participants.""" @@ -47,21 +57,24 @@ class ParticipantsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -128,7 +188,9 @@ 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, @@ -145,33 +207,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.CreateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def get_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.GetParticipantRequest], - typing.Union[ - participant.Participant, typing.Awaitable[participant.Participant] - ], + Union[participant.Participant, Awaitable[participant.Participant]], ]: raise NotImplementedError() @property def list_participants( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListParticipantsRequest], - typing.Union[ + Union[ participant.ListParticipantsResponse, - typing.Awaitable[participant.ListParticipantsResponse], + Awaitable[participant.ListParticipantsResponse], ], ]: raise NotImplementedError() @@ -179,22 +237,20 @@ def list_participants( @property def update_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.UpdateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def analyze_content( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.AnalyzeContentRequest], - typing.Union[ + Union[ gcd_participant.AnalyzeContentResponse, - typing.Awaitable[gcd_participant.AnalyzeContentResponse], + Awaitable[gcd_participant.AnalyzeContentResponse], ], ]: raise NotImplementedError() @@ -202,11 +258,11 @@ def analyze_content( @property def suggest_articles( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestArticlesRequest], - typing.Union[ + Union[ participant.SuggestArticlesResponse, - typing.Awaitable[participant.SuggestArticlesResponse], + Awaitable[participant.SuggestArticlesResponse], ], ]: raise NotImplementedError() @@ -214,11 +270,11 @@ def suggest_articles( @property def suggest_faq_answers( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestFaqAnswersRequest], - typing.Union[ + Union[ participant.SuggestFaqAnswersResponse, - typing.Awaitable[participant.SuggestFaqAnswersResponse], + Awaitable[participant.SuggestFaqAnswersResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc.py index e4543e6bf..51b06e9a3 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2/services/participants/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,21 +13,19 @@ # 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.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - from .base import ParticipantsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) diff --git a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py index 78dc60b4b..138d07b2b 100644 --- a/google/cloud/dialogflow_v2/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/services/participants/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,22 +13,20 @@ # 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.dialogflow_v2.types import participant from google.cloud.dialogflow_v2.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .grpc import ParticipantsGrpcTransport @@ -55,7 +52,7 @@ class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py b/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py index c0dca267f..cbd406b49 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/session_entity_types/async_client.py b/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py index 0eb8e3f7c..b8c0b6627 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_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 @@ -136,7 +128,7 @@ 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, @@ -173,7 +165,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -212,7 +203,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. @@ -242,7 +232,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 @@ -302,7 +291,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 +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 @@ -402,7 +389,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. @@ -437,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: @@ -468,7 +453,7 @@ async def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_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]] = (), @@ -496,7 +481,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. @@ -531,7 +515,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: @@ -589,7 +572,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. @@ -610,7 +592,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/dialogflow_v2/services/session_entity_types/client.py b/google/cloud/dialogflow_v2/services/session_entity_types/client.py index 01c08eba2..f3044c3e2 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/client.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.types import ( session_entity_type as gcd_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 @@ -242,7 +239,7 @@ 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, @@ -383,7 +380,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. @@ -415,10 +411,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 @@ -476,7 +470,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. @@ -513,10 +506,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 @@ -577,7 +568,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. @@ -616,10 +606,8 @@ def create_session_entity_type( request, gcd_session_entity_type.CreateSessionEntityTypeRequest ): request = gcd_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: @@ -648,7 +636,7 @@ def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_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]] = (), @@ -676,7 +664,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. @@ -715,10 +702,8 @@ def update_session_entity_type( request, gcd_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcd_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: @@ -774,7 +759,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. @@ -797,10 +781,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/dialogflow_v2/services/session_entity_types/pagers.py b/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py index 3242ab3e7..e96bdf32f 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflow_v2/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, diff --git a/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py index 606f91160..633fd32cb 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py index 529860533..69ce0f2cd 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.types import session_entity_type from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_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,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._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[ [gcd_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_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[ [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_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/dialogflow_v2/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py index d68070365..9b01b6dd0 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.types import ( session_entity_type as gcd_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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -361,7 +361,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. @@ -383,7 +385,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py index feaffcd71..ed5ff7cca 100644 --- a/google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.types import ( session_entity_type as gcd_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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -366,7 +365,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. @@ -389,7 +388,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2.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/dialogflow_v2/services/sessions/__init__.py b/google/cloud/dialogflow_v2/services/sessions/__init__.py index 3b2a59a9d..0adeafb97 100644 --- a/google/cloud/dialogflow_v2/services/sessions/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/sessions/async_client.py b/google/cloud/dialogflow_v2/services/sessions/async_client.py index e479f1bce..43eeac7b3 100644 --- a/google/cloud/dialogflow_v2/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2/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,17 +29,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.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -69,25 +66,20 @@ class SessionsAsyncClient: parse_session_entity_type_path = staticmethod( SessionsClient.parse_session_entity_type_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) @@ -139,7 +131,7 @@ 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, @@ -176,7 +168,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -247,7 +238,6 @@ async def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -274,7 +264,6 @@ async def detect_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2/services/sessions/client.py b/google/cloud/dialogflow_v2/services/sessions/client.py index f601843e0..e96d078d9 100644 --- a/google/cloud/dialogflow_v2/services/sessions/client.py +++ b/google/cloud/dialogflow_v2/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,8 +43,7 @@ from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -291,7 +288,7 @@ 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, @@ -464,7 +461,6 @@ def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -493,10 +489,8 @@ def detect_intent( # there are no flattened fields. if not isinstance(request, gcd_session.DetectIntentRequest): request = gcd_session.DetectIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py b/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py index 0ca6c76ea..db0f7d045 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflow_v2/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/dialogflow_v2/services/sessions/transports/base.py b/google/cloud/dialogflow_v2/services/sessions/transports/base.py index 4441c222d..fd9173f8a 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2/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,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.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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.""" @@ -47,21 +57,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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -116,7 +176,9 @@ 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, @@ -132,11 +194,11 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session.DetectIntentRequest], - typing.Union[ + Union[ gcd_session.DetectIntentResponse, - typing.Awaitable[gcd_session.DetectIntentResponse], + Awaitable[gcd_session.DetectIntentResponse], ], ]: raise NotImplementedError() @@ -144,11 +206,11 @@ def detect_intent( @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() diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py index 995202acf..f497eb6e5 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2/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,21 +13,19 @@ # 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.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - from .base import SessionsTransport, 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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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, ) diff --git a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py index 69689dd2a..f3128aae5 100644 --- a/google/cloud/dialogflow_v2/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2/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,22 +13,20 @@ # 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.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -57,7 +54,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, @@ -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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2/services/versions/__init__.py b/google/cloud/dialogflow_v2/services/versions/__init__.py new file mode 100644 index 000000000..586be1818 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + "VersionsClient", + "VersionsAsyncClient", +) diff --git a/google/cloud/dialogflow_v2/services/versions/async_client.py b/google/cloud/dialogflow_v2/services/versions/async_client.py new file mode 100644 index 000000000..d8ecb07e1 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/async_client.py @@ -0,0 +1,623 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_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 + + +class VersionsAsyncClient: + """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + 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. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Return the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(VersionsClient).get_transport_class, type(VersionsClient) + ) + + def __init__( + self, + *, + 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. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = version.ListVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 = version.GetVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to create. + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_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: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_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: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + 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( + (("version.name", request.version.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = version.DeleteVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("VersionsAsyncClient",) diff --git a/google/cloud/dialogflow_v2/services/versions/client.py b/google/cloud/dialogflow_v2/services/versions/client.py new file mode 100644 index 000000000..30760f2ce --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/client.py @@ -0,0 +1,808 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import field_mask_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 + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VersionsClient(metaclass=VersionsClientMeta): + """Service for managing [Versions][google.cloud.dialogflow.v2.Version].""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Return the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def version_path(project: str, version: str,) -> str: + """Return a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str, str]: + """Parse a version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/agent/versions/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[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. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (google.cloud.dialogflow_v2.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (google.cloud.dialogflow_v2.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (google.cloud.dialogflow_v2.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_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: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (google.cloud.dialogflow_v2.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_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: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("version.name", request.version.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (google.cloud.dialogflow_v2.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("VersionsClient",) diff --git a/google/cloud/dialogflow_v2/services/versions/pagers.py b/google/cloud/dialogflow_v2/services/versions/pagers.py new file mode 100644 index 000000000..570aeccf3 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +from google.cloud.dialogflow_v2.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2/services/versions/transports/__init__.py b/google/cloud/dialogflow_v2/services/versions/transports/__init__.py new file mode 100644 index 000000000..c5a42a0e8 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry["grpc"] = VersionsGrpcTransport +_transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + +__all__ = ( + "VersionsTransport", + "VersionsGrpcTransport", + "VersionsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflow_v2/services/versions/transports/base.py b/google/cloud/dialogflow_v2/services/versions/transports/base.py new file mode 100644 index 000000000..2ff8e9d06 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # 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. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, default_timeout=None, client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, default_timeout=None, client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, default_timeout=None, client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, default_timeout=None, client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, default_timeout=None, client_info=client_info, + ), + } + + @property + def list_versions( + self, + ) -> Callable[ + [version.ListVersionsRequest], + Union[version.ListVersionsResponse, Awaitable[version.ListVersionsResponse]], + ]: + raise NotImplementedError() + + @property + def get_version( + self, + ) -> Callable[ + [version.GetVersionRequest], Union[version.Version, Awaitable[version.Version]] + ]: + raise NotImplementedError() + + @property + def create_version( + self, + ) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[gcd_version.Version, Awaitable[gcd_version.Version]], + ]: + raise NotImplementedError() + + @property + def update_version( + self, + ) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[gcd_version.Version, Awaitable[gcd_version.Version]], + ]: + raise NotImplementedError() + + @property + def delete_version( + self, + ) -> Callable[ + [version.DeleteVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + +__all__ = ("VersionsTransport",) diff --git a/google/cloud/dialogflow_v2/services/versions/transports/grpc.py b/google/cloud/dialogflow_v2/services/versions/transports/grpc.py new file mode 100644 index 000000000..517e8196a --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/transports/grpc.py @@ -0,0 +1,362 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_versions( + self, + ) -> Callable[[version.ListVersionsRequest], version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_versions" not in self._stubs: + self._stubs["list_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/ListVersions", + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs["list_versions"] + + @property + def get_version(self) -> Callable[[version.GetVersionRequest], version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + 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_version" not in self._stubs: + self._stubs["get_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/GetVersion", + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs["get_version"] + + @property + def create_version( + self, + ) -> Callable[[gcd_version.CreateVersionRequest], gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_version" not in self._stubs: + self._stubs["create_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/CreateVersion", + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["create_version"] + + @property + def update_version( + self, + ) -> Callable[[gcd_version.UpdateVersionRequest], gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_version" not in self._stubs: + self._stubs["update_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/UpdateVersion", + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["update_version"] + + @property + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_version" not in self._stubs: + self._stubs["delete_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/DeleteVersion", + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_version"] + + +__all__ = ("VersionsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py new file mode 100644 index 000000000..5efe9b1e8 --- /dev/null +++ b/google/cloud/dialogflow_v2/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,369 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing [Versions][google.cloud.dialogflow.v2.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + 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, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_versions( + self, + ) -> Callable[ + [version.ListVersionsRequest], Awaitable[version.ListVersionsResponse] + ]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_versions" not in self._stubs: + self._stubs["list_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/ListVersions", + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs["list_versions"] + + @property + def get_version( + self, + ) -> Callable[[version.GetVersionRequest], Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + 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_version" not in self._stubs: + self._stubs["get_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/GetVersion", + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs["get_version"] + + @property + def create_version( + self, + ) -> Callable[[gcd_version.CreateVersionRequest], Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_version" not in self._stubs: + self._stubs["create_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/CreateVersion", + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["create_version"] + + @property + def update_version( + self, + ) -> Callable[[gcd_version.UpdateVersionRequest], Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_version" not in self._stubs: + self._stubs["update_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/UpdateVersion", + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["update_version"] + + @property + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_version" not in self._stubs: + self._stubs["delete_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2.Versions/DeleteVersion", + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_version"] + + +__all__ = ("VersionsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2/types/__init__.py b/google/cloud/dialogflow_v2/types/__init__.py index ba48aa9da..7426db72a 100644 --- a/google/cloud/dialogflow_v2/types/__init__.py +++ b/google/cloud/dialogflow_v2/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, DeleteAgentRequest, @@ -116,9 +114,21 @@ UpdateEntityTypeRequest, ) from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, ListEnvironmentsRequest, ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, ) from .human_agent_assistant_event import HumanAgentAssistantEvent from .intent import ( @@ -195,6 +205,15 @@ ValidationError, ValidationResult, ) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) from .webhook import ( OriginalDetectIntentRequest, WebhookRequest, @@ -286,9 +305,19 @@ "ListEntityTypesRequest", "ListEntityTypesResponse", "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", "HumanAgentAssistantEvent", "BatchDeleteIntentsRequest", "BatchUpdateIntentsRequest", @@ -352,6 +381,13 @@ "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", diff --git a/google/cloud/dialogflow_v2/types/agent.py b/google/cloud/dialogflow_v2/types/agent.py index 9309c84bc..7cee91fec 100644 --- a/google/cloud/dialogflow_v2/types/agent.py +++ b/google/cloud/dialogflow_v2/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,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( @@ -133,28 +130,17 @@ class Tier(proto.Enum): TIER_ENTERPRISE = 2 TIER_ENTERPRISE_PLUS = 3 - parent = 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) - - enable_logging = proto.Field(proto.BOOL, number=8) - + parent = 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,) + enable_logging = proto.Field(proto.BOOL, number=8,) match_mode = proto.Field(proto.ENUM, number=9, enum=MatchMode,) - - classification_threshold = proto.Field(proto.FLOAT, number=10) - + classification_threshold = proto.Field(proto.FLOAT, number=10,) api_version = proto.Field(proto.ENUM, number=14, enum=ApiVersion,) - tier = proto.Field(proto.ENUM, number=15, enum=Tier,) @@ -168,7 +154,7 @@ class GetAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SetAgentRequest(proto.Message): @@ -184,8 +170,9 @@ class SetAgentRequest(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): @@ -198,7 +185,7 @@ class DeleteAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SearchAgentsRequest(proto.Message): @@ -218,11 +205,9 @@ class SearchAgentsRequest(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 SearchAgentsResponse(proto.Message): @@ -244,8 +229,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 TrainAgentRequest(proto.Message): @@ -258,7 +242,7 @@ class TrainAgentRequest(proto.Message): with. Format: ``projects/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -277,9 +261,8 @@ class ExportAgentRequest(proto.Message): the serialized agent is returned inline. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) class ExportAgentResponse(proto.Message): @@ -295,9 +278,8 @@ class ExportAgentResponse(proto.Message): Zip compressed 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 ImportAgentRequest(proto.Message): @@ -316,11 +298,9 @@ class ImportAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = 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") + parent = 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",) class RestoreAgentRequest(proto.Message): @@ -339,11 +319,9 @@ class RestoreAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = 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") + parent = 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",) class GetValidationResultRequest(proto.Message): @@ -363,9 +341,8 @@ class GetValidationResultRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/answer_record.py b/google/cloud/dialogflow_v2/types/answer_record.py index 57866e0e5..92a8accd9 100644 --- a/google/cloud/dialogflow_v2/types/answer_record.py +++ b/google/cloud/dialogflow_v2/types/answer_record.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.dialogflow_v2.types import participant -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( @@ -81,10 +78,8 @@ class AnswerRecord(proto.Message): assistant. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) answer_feedback = proto.Field(proto.MESSAGE, number=2, message="AnswerFeedback",) - agent_assistant_record = proto.Field( proto.MESSAGE, number=4, oneof="record", message="AgentAssistantRecord", ) @@ -119,13 +114,10 @@ class ListAnswerRecordsRequest(proto.Message): listing on the next page. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListAnswerRecordsResponse(proto.Message): @@ -150,8 +142,7 @@ def raw_page(self): answer_records = proto.RepeatedField( proto.MESSAGE, number=1, message="AnswerRecord", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateAnswerRecordRequest(proto.Message): @@ -167,8 +158,9 @@ class UpdateAnswerRecordRequest(proto.Message): """ answer_record = proto.Field(proto.MESSAGE, number=1, message="AnswerRecord",) - - 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 AnswerFeedback(proto.Message): @@ -201,26 +193,22 @@ class CorrectnessLevel(proto.Enum): FULLY_CORRECT = 3 correctness_level = proto.Field(proto.ENUM, number=1, enum=CorrectnessLevel,) - agent_assistant_detail_feedback = proto.Field( proto.MESSAGE, number=2, oneof="detail_feedback", message="AgentAssistantFeedback", ) - - clicked = proto.Field(proto.BOOL, number=3) - - click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - displayed = proto.Field(proto.BOOL, number=4) - - display_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + clicked = proto.Field(proto.BOOL, number=3,) + click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + displayed = proto.Field(proto.BOOL, number=4,) + display_time = proto.Field( + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, + ) class AgentAssistantFeedback(proto.Message): r"""Detail feedback of Agent Assist result. - Attributes: answer_relevance (google.cloud.dialogflow_v2.types.AgentAssistantFeedback.AnswerRelevance): Optional. Whether or not the suggested answer is relevant. @@ -273,15 +261,12 @@ class DocumentEfficiency(proto.Enum): EFFICIENT = 2 answer_relevance = proto.Field(proto.ENUM, number=1, enum=AnswerRelevance,) - document_correctness = proto.Field(proto.ENUM, number=2, enum=DocumentCorrectness,) - document_efficiency = proto.Field(proto.ENUM, number=3, enum=DocumentEfficiency,) class AgentAssistantRecord(proto.Message): r"""Represents a record of a human agent assist answer. - Attributes: article_suggestion_answer (google.cloud.dialogflow_v2.types.ArticleAnswer): Output only. The article suggestion answer. @@ -292,7 +277,6 @@ class AgentAssistantRecord(proto.Message): article_suggestion_answer = proto.Field( proto.MESSAGE, number=5, oneof="answer", message=participant.ArticleAnswer, ) - faq_answer = proto.Field( proto.MESSAGE, number=6, oneof="answer", message=participant.FaqAnswer, ) diff --git a/google/cloud/dialogflow_v2/types/audio_config.py b/google/cloud/dialogflow_v2/types/audio_config.py index 4b8ecf6d8..5cca3a22f 100644 --- a/google/cloud/dialogflow_v2/types/audio_config.py +++ b/google/cloud/dialogflow_v2/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( @@ -127,14 +124,12 @@ class SpeechContext(proto.Message): binary search. """ - phrases = proto.RepeatedField(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=2) + phrases = proto.RepeatedField(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=2,) class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -161,13 +156,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): @@ -254,31 +246,21 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) speech_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message="SpeechContext", ) - - model = proto.Field(proto.STRING, number=7) - + 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) - - disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14) + single_utterance = proto.Field(proto.BOOL, number=8,) + disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14,) 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 @@ -296,14 +278,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 @@ -337,14 +317,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",) @@ -373,9 +349,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/dialogflow_v2/types/context.py b/google/cloud/dialogflow_v2/types/context.py index 72e6564de..0b16c4140 100644 --- a/google/cloud/dialogflow_v2/types/context.py +++ b/google/cloud/dialogflow_v2/types/context.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 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( @@ -105,11 +102,9 @@ class Context(proto.Message): Else: parameter value """ - name = proto.Field(proto.STRING, number=1) - - lifespan_count = proto.Field(proto.INT32, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + name = proto.Field(proto.STRING, number=1,) + lifespan_count = proto.Field(proto.INT32, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) class ListContextsRequest(proto.Message): @@ -133,11 +128,9 @@ class ListContextsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListContextsResponse(proto.Message): @@ -159,8 +152,7 @@ def raw_page(self): return self contexts = proto.RepeatedField(proto.MESSAGE, number=1, message="Context",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetContextRequest(proto.Message): @@ -178,7 +170,7 @@ class GetContextRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateContextRequest(proto.Message): @@ -197,8 +189,7 @@ class CreateContextRequest(proto.Message): Required. The context to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) context = proto.Field(proto.MESSAGE, number=2, message="Context",) @@ -215,8 +206,9 @@ class UpdateContextRequest(proto.Message): """ context = proto.Field(proto.MESSAGE, number=1, message="Context",) - - 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 DeleteContextRequest(proto.Message): @@ -234,7 +226,7 @@ class DeleteContextRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteAllContextsRequest(proto.Message): @@ -252,7 +244,7 @@ class DeleteAllContextsRequest(proto.Message): assume default '-' user. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/conversation.py b/google/cloud/dialogflow_v2/types/conversation.py index a53db5ebe..f6d392fef 100644 --- a/google/cloud/dialogflow_v2/types/conversation.py +++ b/google/cloud/dialogflow_v2/types/conversation.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.dialogflow_v2.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -102,20 +99,14 @@ class ConversationStage(proto.Enum): VIRTUAL_AGENT_STAGE = 1 HUMAN_ASSIST_STAGE = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) lifecycle_state = proto.Field(proto.ENUM, number=2, enum=LifecycleState,) - - conversation_profile = proto.Field(proto.STRING, number=3) - + conversation_profile = proto.Field(proto.STRING, number=3,) phone_number = proto.Field( proto.MESSAGE, number=4, message="ConversationPhoneNumber", ) - - start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) conversation_stage = proto.Field(proto.ENUM, number=7, enum=ConversationStage,) @@ -146,11 +137,9 @@ class CreateConversationRequest(proto.Message): a project to better ensure uniqueness. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation = proto.Field(proto.MESSAGE, number=2, message="Conversation",) - - conversation_id = proto.Field(proto.STRING, number=3) + conversation_id = proto.Field(proto.STRING, number=3,) class ListConversationsRequest(proto.Message): @@ -192,13 +181,10 @@ class ListConversationsRequest(proto.Message): Filtering `__. """ - 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 ListConversationsResponse(proto.Message): @@ -222,8 +208,7 @@ def raw_page(self): conversations = proto.RepeatedField( proto.MESSAGE, number=1, message="Conversation", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationRequest(proto.Message): @@ -236,7 +221,7 @@ class GetConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CompleteConversationRequest(proto.Message): @@ -250,7 +235,7 @@ class CompleteConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListMessagesRequest(proto.Message): @@ -281,13 +266,10 @@ class ListMessagesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListMessagesResponse(proto.Message): @@ -313,8 +295,7 @@ def raw_page(self): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=participant.Message, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ConversationPhoneNumber(proto.Message): @@ -327,7 +308,7 @@ class ConversationPhoneNumber(proto.Message): this conversation. """ - phone_number = proto.Field(proto.STRING, number=3) + phone_number = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/conversation_event.py b/google/cloud/dialogflow_v2/types/conversation_event.py index 1f6551e7a..193259b4f 100644 --- a/google/cloud/dialogflow_v2/types/conversation_event.py +++ b/google/cloud/dialogflow_v2/types/conversation_event.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.dialogflow_v2.types import participant -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -55,12 +52,9 @@ class Type(proto.Enum): NEW_MESSAGE = 5 UNRECOVERABLE_ERROR = 4 - conversation = proto.Field(proto.STRING, number=1) - + conversation = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - error_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - + error_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) new_message_payload = proto.Field( proto.MESSAGE, number=4, oneof="payload", message=participant.Message, ) diff --git a/google/cloud/dialogflow_v2/types/conversation_profile.py b/google/cloud/dialogflow_v2/types/conversation_profile.py index c792728dd..b7022be1b 100644 --- a/google/cloud/dialogflow_v2/types/conversation_profile.py +++ b/google/cloud/dialogflow_v2/types/conversation_profile.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.dialogflow_v2.types import audio_config -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,8 +46,7 @@ class ConversationProfile(proto.Message): Attributes: name (str): - Optional. The unique identifier of this conversation - profile. Format: + The unique identifier of this conversation profile. Format: ``projects//locations//conversationProfiles/``. display_name (str): Required. Human readable name for this @@ -69,6 +65,8 @@ class ConversationProfile(proto.Message): with this profile. human_agent_handoff_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig): Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): Configuration for publishing conversation lifecycle events. @@ -89,41 +87,34 @@ class ConversationProfile(proto.Message): they want to support. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - create_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=12, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=11, message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, number=12, message=timestamp_pb2.Timestamp, + ) automated_agent_config = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentConfig", ) - human_agent_assistant_config = proto.Field( proto.MESSAGE, number=4, message="HumanAgentAssistantConfig", ) - human_agent_handoff_config = proto.Field( proto.MESSAGE, number=5, message="HumanAgentHandoffConfig", ) - notification_config = proto.Field( proto.MESSAGE, number=6, message="NotificationConfig", ) - logging_config = proto.Field(proto.MESSAGE, number=7, message="LoggingConfig",) - new_message_event_notification_config = proto.Field( proto.MESSAGE, number=8, message="NotificationConfig", ) - stt_config = proto.Field( proto.MESSAGE, number=9, message=audio_config.SpeechToTextConfig, ) - - language_code = proto.Field(proto.STRING, number=10) + language_code = proto.Field(proto.STRING, number=10,) class ListConversationProfilesRequest(proto.Message): @@ -143,11 +134,9 @@ class ListConversationProfilesRequest(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 ListConversationProfilesResponse(proto.Message): @@ -172,8 +161,7 @@ def raw_page(self): conversation_profiles = proto.RepeatedField( proto.MESSAGE, number=1, message="ConversationProfile", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationProfileRequest(proto.Message): @@ -187,7 +175,7 @@ class GetConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateConversationProfileRequest(proto.Message): @@ -202,8 +190,7 @@ class CreateConversationProfileRequest(proto.Message): Required. The conversation profile to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation_profile = proto.Field( proto.MESSAGE, number=2, message="ConversationProfile", ) @@ -224,8 +211,9 @@ class UpdateConversationProfileRequest(proto.Message): conversation_profile = proto.Field( proto.MESSAGE, number=1, message="ConversationProfile", ) - - 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 DeleteConversationProfileRequest(proto.Message): @@ -242,12 +230,11 @@ class DeleteConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class AutomatedAgentConfig(proto.Message): r"""Defines the Automated Agent to connect to a conversation. - Attributes: agent (str): Required. ID of the Dialogflow agent environment to use. @@ -265,12 +252,11 @@ class AutomatedAgentConfig(proto.Message): for more details. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class HumanAgentAssistantConfig(proto.Message): r"""Defines the Human Agent Assist to connect to a conversation. - Attributes: notification_config (google.cloud.dialogflow_v2.types.NotificationConfig): Pub/Sub topic on which to publish new agent @@ -281,13 +267,14 @@ class HumanAgentAssistantConfig(proto.Message): end_user_suggestion_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionConfig): Configuration for agent assistance of end user participant. + Currently, this feature is not general + available, please contact Google to get access. message_analysis_config (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.MessageAnalysisConfig): Configuration for message analysis. """ class SuggestionTriggerSettings(proto.Message): r"""Settings of suggestion trigger. - Attributes: no_smalltalk (bool): Do not trigger if last utterance is small @@ -297,13 +284,11 @@ class SuggestionTriggerSettings(proto.Message): utterance is END_USER. """ - no_smalltalk = proto.Field(proto.BOOL, number=1) - - only_end_user = proto.Field(proto.BOOL, number=2) + no_smalltalk = proto.Field(proto.BOOL, number=1,) + only_end_user = proto.Field(proto.BOOL, number=2,) class SuggestionFeatureConfig(proto.Message): r"""Config for suggestion features. - Attributes: suggestion_feature (google.cloud.dialogflow_v2.types.SuggestionFeature): The suggestion feature. @@ -327,21 +312,17 @@ class SuggestionFeatureConfig(proto.Message): suggestion_feature = proto.Field( proto.MESSAGE, number=5, message="SuggestionFeature", ) - - enable_event_based_suggestion = proto.Field(proto.BOOL, number=3) - + enable_event_based_suggestion = proto.Field(proto.BOOL, number=3,) suggestion_trigger_settings = proto.Field( proto.MESSAGE, number=10, message="HumanAgentAssistantConfig.SuggestionTriggerSettings", ) - query_config = proto.Field( proto.MESSAGE, number=6, message="HumanAgentAssistantConfig.SuggestionQueryConfig", ) - conversation_model_config = proto.Field( proto.MESSAGE, number=7, @@ -350,7 +331,6 @@ class SuggestionFeatureConfig(proto.Message): class SuggestionConfig(proto.Message): r"""Detail human agent assistant config. - Attributes: feature_configs (Sequence[google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): Configuration of different suggestion @@ -375,12 +355,10 @@ class SuggestionConfig(proto.Message): number=2, message="HumanAgentAssistantConfig.SuggestionFeatureConfig", ) - - group_suggestion_responses = proto.Field(proto.BOOL, number=3) + group_suggestion_responses = proto.Field(proto.BOOL, number=3,) class SuggestionQueryConfig(proto.Message): r"""Config for suggestion query. - Attributes: knowledge_base_query_source (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, @@ -434,7 +412,7 @@ class KnowledgeBaseQuerySource(proto.Message): Currently, at most 5 knowledge bases are supported. """ - knowledge_bases = proto.RepeatedField(proto.STRING, number=1) + knowledge_bases = proto.RepeatedField(proto.STRING, number=1,) class DocumentQuerySource(proto.Message): r"""Document source settings. @@ -448,7 +426,7 @@ class DocumentQuerySource(proto.Message): Currently, at most 5 documents are supported. """ - documents = proto.RepeatedField(proto.STRING, number=1) + documents = proto.RepeatedField(proto.STRING, number=1,) class DialogflowQuerySource(proto.Message): r"""Dialogflow source setting. @@ -464,7 +442,7 @@ class DialogflowQuerySource(proto.Message): project. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class ContextFilterSettings(proto.Message): r"""Settings that determine how to filter recent conversation @@ -483,11 +461,9 @@ class ContextFilterSettings(proto.Message): are dropped. """ - drop_handoff_messages = proto.Field(proto.BOOL, number=1) - - drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2) - - drop_ivr_messages = proto.Field(proto.BOOL, number=3) + drop_handoff_messages = proto.Field(proto.BOOL, number=1,) + drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2,) + drop_ivr_messages = proto.Field(proto.BOOL, number=3,) knowledge_base_query_source = proto.Field( proto.MESSAGE, @@ -495,25 +471,20 @@ class ContextFilterSettings(proto.Message): oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource", ) - document_query_source = proto.Field( proto.MESSAGE, number=2, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource", ) - dialogflow_query_source = proto.Field( proto.MESSAGE, number=3, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource", ) - - max_results = proto.Field(proto.INT32, number=4) - - confidence_threshold = proto.Field(proto.FLOAT, number=5) - + max_results = proto.Field(proto.INT32, number=4,) + confidence_threshold = proto.Field(proto.FLOAT, number=5,) context_filter_settings = proto.Field( proto.MESSAGE, number=7, @@ -527,11 +498,11 @@ class ConversationModelConfig(proto.Message): Attributes: model (str): - Required. Conversation model resource name. Format: + Conversation model resource name. Format: ``projects//conversationModels/``. """ - model = proto.Field(proto.STRING, number=1) + model = proto.Field(proto.STRING, number=1,) class MessageAnalysisConfig(proto.Message): r"""Configuration for analyses to run on each conversation @@ -543,6 +514,9 @@ class MessageAnalysisConfig(proto.Message): assist stage `__. If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. enable_sentiment_analysis (bool): Enable sentiment analysis in conversation messages on `agent assist @@ -568,22 +542,18 @@ class MessageAnalysisConfig(proto.Message): [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2.ConversationEvent.new_message_payload]. """ - enable_entity_extraction = proto.Field(proto.BOOL, number=2) - - enable_sentiment_analysis = proto.Field(proto.BOOL, number=3) + enable_entity_extraction = proto.Field(proto.BOOL, number=2,) + enable_sentiment_analysis = proto.Field(proto.BOOL, number=3,) notification_config = proto.Field( proto.MESSAGE, number=2, message="NotificationConfig", ) - human_agent_suggestion_config = proto.Field( proto.MESSAGE, number=3, message=SuggestionConfig, ) - end_user_suggestion_config = proto.Field( proto.MESSAGE, number=4, message=SuggestionConfig, ) - message_analysis_config = proto.Field( proto.MESSAGE, number=5, message=MessageAnalysisConfig, ) @@ -592,6 +562,8 @@ class MessageAnalysisConfig(proto.Message): class HumanAgentHandoffConfig(proto.Message): r"""Defines the hand off to a live agent, typically on which external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. Attributes: live_person_config (google.cloud.dialogflow_v2.types.HumanAgentHandoffConfig.LivePersonConfig): @@ -611,11 +583,10 @@ class LivePersonConfig(proto.Message): you input at the login page. """ - account_number = proto.Field(proto.STRING, number=1) + account_number = proto.Field(proto.STRING, number=1,) class SalesforceLiveAgentConfig(proto.Message): r"""Configuration specific to Salesforce Live Agent. - Attributes: organization_id (str): Required. The organization ID of the @@ -632,18 +603,14 @@ class SalesforceLiveAgentConfig(proto.Message): fill in d.la4-c2-phx.salesforceliveagent.com. """ - organization_id = proto.Field(proto.STRING, number=1) - - deployment_id = proto.Field(proto.STRING, number=2) - - button_id = proto.Field(proto.STRING, number=3) - - endpoint_domain = proto.Field(proto.STRING, number=4) + organization_id = proto.Field(proto.STRING, number=1,) + deployment_id = proto.Field(proto.STRING, number=2,) + button_id = proto.Field(proto.STRING, number=3,) + endpoint_domain = proto.Field(proto.STRING, number=4,) live_person_config = proto.Field( proto.MESSAGE, number=1, oneof="agent_service", message=LivePersonConfig, ) - salesforce_live_agent_config = proto.Field( proto.MESSAGE, number=2, @@ -654,7 +621,6 @@ class SalesforceLiveAgentConfig(proto.Message): class NotificationConfig(proto.Message): r"""Defines notification behavior. - Attributes: topic (str): Name of the Pub/Sub topic to publish conversation events @@ -681,14 +647,12 @@ class MessageFormat(proto.Enum): PROTO = 1 JSON = 2 - topic = proto.Field(proto.STRING, number=1) - + topic = proto.Field(proto.STRING, number=1,) message_format = proto.Field(proto.ENUM, number=2, enum=MessageFormat,) class LoggingConfig(proto.Message): r"""Defines logging behavior for conversation lifecycle events. - Attributes: enable_stackdriver_logging (bool): Whether to log conversation events like @@ -698,7 +662,7 @@ class LoggingConfig(proto.Message): protos. """ - enable_stackdriver_logging = proto.Field(proto.BOOL, number=3) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=3,) class SuggestionFeature(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/document.py b/google/cloud/dialogflow_v2/types/document.py index d04fe2188..3b3861829 100644 --- a/google/cloud/dialogflow_v2/types/document.py +++ b/google/cloud/dialogflow_v2/types/document.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 field_mask_pb2 as field_mask # 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 timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -118,7 +115,6 @@ class KnowledgeType(proto.Enum): class ReloadStatus(proto.Message): r"""The status of a reload attempt. - Attributes: time (google.protobuf.timestamp_pb2.Timestamp): The time of a reload attempt. @@ -130,27 +126,18 @@ class ReloadStatus(proto.Message): load. """ - time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - + time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) knowledge_types = proto.RepeatedField(proto.ENUM, number=4, enum=KnowledgeType,) - - content_uri = proto.Field(proto.STRING, number=5, oneof="source") - - raw_content = proto.Field(proto.BYTES, number=9, oneof="source") - - enable_auto_reload = proto.Field(proto.BOOL, number=11) - + content_uri = proto.Field(proto.STRING, number=5, oneof="source",) + raw_content = proto.Field(proto.BYTES, number=9, oneof="source",) + enable_auto_reload = proto.Field(proto.BOOL, number=11,) latest_reload_status = proto.Field(proto.MESSAGE, number=12, message=ReloadStatus,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=7) + metadata = proto.MapField(proto.STRING, proto.STRING, number=7,) class GetDocumentRequest(proto.Message): @@ -163,7 +150,7 @@ class GetDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListDocumentsRequest(proto.Message): @@ -183,11 +170,9 @@ class ListDocumentsRequest(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 ListDocumentsResponse(proto.Message): @@ -208,8 +193,7 @@ def raw_page(self): return self documents = proto.RepeatedField(proto.MESSAGE, number=1, message="Document",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateDocumentRequest(proto.Message): @@ -225,8 +209,7 @@ class CreateDocumentRequest(proto.Message): Required. The document to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) document = proto.Field(proto.MESSAGE, number=2, message="Document",) @@ -240,7 +223,7 @@ class DeleteDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateDocumentRequest(proto.Message): @@ -257,8 +240,9 @@ class UpdateDocumentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - - 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 ReloadDocumentRequest(proto.Message): @@ -277,9 +261,8 @@ class ReloadDocumentRequest(proto.Message): must have the form ``gs:///``. """ - name = proto.Field(proto.STRING, number=1) - - content_uri = proto.Field(proto.STRING, number=3, oneof="source") + name = proto.Field(proto.STRING, number=1,) + content_uri = proto.Field(proto.STRING, number=3, oneof="source",) class KnowledgeOperationMetadata(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/entity_type.py b/google/cloud/dialogflow_v2/types/entity_type.py index 3d0214e56..acb5cece1 100644 --- a/google/cloud/dialogflow_v2/types/entity_type.py +++ b/google/cloud/dialogflow_v2/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( @@ -98,7 +95,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 @@ -124,21 +120,15 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) + 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=6, message=Entity,) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) class ListEntityTypesRequest(proto.Message): @@ -164,13 +154,10 @@ class ListEntityTypesRequest(proto.Message): list 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): @@ -193,8 +180,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): @@ -213,9 +199,8 @@ class GetEntityTypeRequest(proto.Message): data `__. """ - 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): @@ -236,11 +221,9 @@ class CreateEntityTypeRequest(proto.Message): data `__. """ - 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): @@ -262,10 +245,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): @@ -278,7 +261,7 @@ class DeleteEntityTypeRequest(proto.Message): ``projects//agent/entityTypes/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateEntityTypesRequest(proto.Message): @@ -309,19 +292,17 @@ class BatchUpdateEntityTypesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type_batch_uri = proto.Field( - proto.STRING, number=2, oneof="entity_type_batch" + proto.STRING, number=2, oneof="entity_type_batch", ) - entity_type_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="entity_type_batch", message="EntityTypeBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) class BatchUpdateEntityTypesResponse(proto.Message): @@ -350,9 +331,8 @@ class BatchDeleteEntityTypesRequest(proto.Message): point to the same agent as ``parent``. """ - parent = proto.Field(proto.STRING, number=1) - - entity_type_names = proto.RepeatedField(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entity_type_names = proto.RepeatedField(proto.STRING, number=2,) class BatchCreateEntitiesRequest(proto.Message): @@ -374,13 +354,11 @@ class BatchCreateEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class BatchUpdateEntitiesRequest(proto.Message): @@ -405,15 +383,14 @@ class BatchUpdateEntitiesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) - - update_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=3,) + update_mask = proto.Field( + proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask, + ) class BatchDeleteEntitiesRequest(proto.Message): @@ -437,11 +414,9 @@ class BatchDeleteEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - - entity_values = proto.RepeatedField(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + entity_values = proto.RepeatedField(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) class EntityTypeBatch(proto.Message): diff --git a/google/cloud/dialogflow_v2/types/environment.py b/google/cloud/dialogflow_v2/types/environment.py index 21f40d80e..204524dc7 100644 --- a/google/cloud/dialogflow_v2/types/environment.py +++ b/google/cloud/dialogflow_v2/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,16 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.cloud.dialogflow_v2.types import audio_config +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.dialogflow.v2", - manifest={"Environment", "ListEnvironmentsRequest", "ListEnvironmentsResponse",}, + manifest={ + "Environment", + "TextToSpeechSettings", + "ListEnvironmentsRequest", + "ListEnvironmentsResponse", + "GetEnvironmentRequest", + "CreateEnvironmentRequest", + "UpdateEnvironmentRequest", + "DeleteEnvironmentRequest", + "GetEnvironmentHistoryRequest", + "EnvironmentHistory", + }, ) @@ -51,9 +62,10 @@ class Environment(proto.Message): Attributes: name (str): Output only. The unique identifier of this agent - environment. Format: - ``projects//agent/environments/``. - For Environment ID, "-" is reserved for 'draft' environment. + environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` description (str): Optional. The developer-provided description for this environment. The maximum length is 500 @@ -61,8 +73,10 @@ class Environment(proto.Message): rejected. agent_version (str): Optional. The agent version loaded into this environment. - Format: - ``projects//agent/versions/``. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` state (google.cloud.dialogflow_v2.types.Environment.State): Output only. The state of this environment. This field is read-only, i.e., it cannot be set @@ -71,6 +85,12 @@ class Environment(proto.Message): Output only. The last update time of this environment. This field is read-only, i.e., it cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. """ class State(proto.Enum): @@ -86,15 +106,58 @@ class State(proto.Enum): LOADING = 2 RUNNING = 3 - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + agent_version = proto.Field(proto.STRING, number=3,) + state = proto.Field(proto.ENUM, number=4, enum=State,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + text_to_speech_settings = proto.Field( + proto.MESSAGE, number=7, message="TextToSpeechSettings", + ) + fulfillment = proto.Field( + proto.MESSAGE, number=8, message=gcd_fulfillment.Fulfillment, + ) - description = proto.Field(proto.STRING, number=2) - agent_version = proto.Field(proto.STRING, number=3) +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. - state = proto.Field(proto.ENUM, number=4, enum=State,) + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + enable_text_to_speech = proto.Field(proto.BOOL, number=1,) + output_audio_encoding = proto.Field( + proto.ENUM, number=2, enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field(proto.INT32, number=3,) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) class ListEnvironmentsRequest(proto.Message): @@ -104,7 +167,9 @@ class ListEnvironmentsRequest(proto.Message): Attributes: parent (str): Required. The agent to list all environments from. Format: - ``projects//agent``. + + - ``projects//agent`` + - ``projects//locations//agent`` page_size (int): Optional. The maximum number of items to return in a single page. By default 100 and at @@ -114,11 +179,9 @@ class ListEnvironmentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + 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 +204,160 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) + environment_id = proto.Field(proto.STRING, number=3,) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field(proto.BOOL, number=3,) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self - next_page_token = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entries = proto.RepeatedField(proto.MESSAGE, number=2, message=Entry,) + next_page_token = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/fulfillment.py b/google/cloud/dialogflow_v2/types/fulfillment.py new file mode 100644 index 000000000..c867a5c3f --- /dev/null +++ b/google/cloud/dialogflow_v2/types/fulfillment.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={"Fulfillment", "GetFulfillmentRequest", "UpdateFulfillmentRequest",}, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + Optional. The human-readable name of the + fulfillment, unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + enabled (bool): + Optional. Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.Feature]): + Optional. The field defines whether the + fulfillment is enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + Optional. The user name for HTTP Basic + authentication. + password (str): + Optional. The password for HTTP Basic + authentication. + request_headers (Sequence[google.cloud.dialogflow_v2.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + Optional. The HTTP request headers to send + together with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + 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,) + is_cloud_function = proto.Field(proto.BOOL, number=5,) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + Attributes: + type_ (google.cloud.dialogflow_v2.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field(proto.ENUM, number=1, enum="Fulfillment.Feature.Type",) + + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + generic_web_service = proto.Field( + proto.MESSAGE, number=3, oneof="fulfillment", message=GenericWebService, + ) + enabled = proto.Field(proto.BOOL, number=4,) + features = proto.RepeatedField(proto.MESSAGE, number=5, message=Feature,) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Format: + ``projects//agent/fulfillment``. + """ + + name = proto.Field(proto.STRING, number=1,) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field(proto.MESSAGE, number=1, message="Fulfillment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/gcs.py b/google/cloud/dialogflow_v2/types/gcs.py index 5f0961da2..8076c8a39 100644 --- a/google/cloud/dialogflow_v2/types/gcs.py +++ b/google/cloud/dialogflow_v2/types/gcs.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/dialogflow_v2/types/human_agent_assistant_event.py b/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py index 48fdc4371..74a0afacf 100644 --- a/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py +++ b/google/cloud/dialogflow_v2/types/human_agent_assistant_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import participant as gcd_participant @@ -43,10 +40,8 @@ class HumanAgentAssistantEvent(proto.Message): notification refers to. """ - conversation = proto.Field(proto.STRING, number=1) - - participant = proto.Field(proto.STRING, number=3) - + conversation = proto.Field(proto.STRING, number=1,) + participant = proto.Field(proto.STRING, number=3,) suggestion_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_participant.SuggestionResult, ) diff --git a/google/cloud/dialogflow_v2/types/intent.py b/google/cloud/dialogflow_v2/types/intent.py index 5c7505576..6056300c4 100644 --- a/google/cloud/dialogflow_v2/types/intent.py +++ b/google/cloud/dialogflow_v2/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,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import context -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( @@ -178,7 +175,6 @@ class WebhookState(proto.Enum): class TrainingPhrase(proto.Message): r"""Represents an example that the agent is trained on. - Attributes: name (str): Output only. The unique identifier of this @@ -225,7 +221,6 @@ class Type(proto.Enum): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -246,27 +241,20 @@ class Part(proto.Message): part with the API, you must set this to true. """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - alias = proto.Field(proto.STRING, number=3) - - user_defined = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + alias = proto.Field(proto.STRING, number=3,) + user_defined = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum="Intent.TrainingPhrase.Type",) - parts = proto.RepeatedField( proto.MESSAGE, number=3, message="Intent.TrainingPhrase.Part", ) - - times_added_count = proto.Field(proto.INT32, number=4) + times_added_count = proto.Field(proto.INT32, number=4,) class Parameter(proto.Message): r"""Represents intent parameters. - Attributes: name (str): The unique identifier of this parameter. @@ -304,21 +292,14 @@ class Parameter(proto.Message): represents a list of values. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - value = proto.Field(proto.STRING, number=3) - - default_value = proto.Field(proto.STRING, number=4) - - entity_type_display_name = proto.Field(proto.STRING, number=5) - - mandatory = proto.Field(proto.BOOL, number=6) - - prompts = proto.RepeatedField(proto.STRING, number=7) - - is_list = proto.Field(proto.BOOL, number=8) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + value = proto.Field(proto.STRING, number=3,) + default_value = proto.Field(proto.STRING, number=4,) + entity_type_display_name = proto.Field(proto.STRING, number=5,) + mandatory = proto.Field(proto.BOOL, number=6,) + prompts = proto.RepeatedField(proto.STRING, number=7,) + is_list = proto.Field(proto.BOOL, number=8,) class Message(proto.Message): r"""A rich response message. Corresponds to the intent ``Response`` @@ -381,18 +362,16 @@ class Platform(proto.Enum): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Optional. The collection of the agent's responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class Image(proto.Message): r"""The image response message. - Attributes: image_uri (str): Optional. The public URI to an image file. @@ -401,13 +380,11 @@ class Image(proto.Message): be used for accessibility, e.g., screen readers. """ - image_uri = proto.Field(proto.STRING, number=1) - - accessibility_text = proto.Field(proto.STRING, number=2) + image_uri = proto.Field(proto.STRING, number=1,) + accessibility_text = proto.Field(proto.STRING, number=2,) class QuickReplies(proto.Message): r"""The quick replies response message. - Attributes: title (str): Optional. The title of the collection of @@ -416,13 +393,11 @@ class QuickReplies(proto.Message): Optional. The collection of quick replies. """ - title = proto.Field(proto.STRING, number=1) - - quick_replies = proto.RepeatedField(proto.STRING, number=2) + title = proto.Field(proto.STRING, number=1,) + quick_replies = proto.RepeatedField(proto.STRING, number=2,) class Card(proto.Message): r"""The card response message. - Attributes: title (str): Optional. The title of the card. @@ -437,7 +412,6 @@ class Card(proto.Message): class Button(proto.Message): r"""Contains information about a button. - Attributes: text (str): Optional. The text to show on the button. @@ -446,23 +420,18 @@ class Button(proto.Message): Dialogflow API or a URI to open. """ - text = proto.Field(proto.STRING, number=1) - - postback = proto.Field(proto.STRING, number=2) - - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - image_uri = proto.Field(proto.STRING, number=3) + text = proto.Field(proto.STRING, number=1,) + postback = proto.Field(proto.STRING, number=2,) + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + image_uri = proto.Field(proto.STRING, number=3,) buttons = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.Card.Button", ) class SimpleResponse(proto.Message): r"""The simple response message containing speech or text. - Attributes: text_to_speech (str): One of text_to_speech or ssml must be provided. The plain @@ -475,11 +444,9 @@ class SimpleResponse(proto.Message): Optional. The text to display. """ - text_to_speech = proto.Field(proto.STRING, number=1) - - ssml = proto.Field(proto.STRING, number=2) - - display_text = proto.Field(proto.STRING, number=3) + text_to_speech = proto.Field(proto.STRING, number=1,) + ssml = proto.Field(proto.STRING, number=2,) + display_text = proto.Field(proto.STRING, number=3,) class SimpleResponses(proto.Message): r"""The collection of simple response candidates. This message in @@ -498,7 +465,6 @@ class SimpleResponses(proto.Message): class BasicCard(proto.Message): r"""The basic card message. Useful for displaying information. - Attributes: title (str): Optional. The title of the card. @@ -515,7 +481,6 @@ class BasicCard(proto.Message): class Button(proto.Message): r"""The button object that appears at the bottom of a card. - Attributes: title (str): Required. The title of the button. @@ -526,32 +491,26 @@ class Button(proto.Message): class OpenUriAction(proto.Message): r"""Opens the given URI. - Attributes: uri (str): Required. The HTTP or HTTPS scheme URI. """ - uri = proto.Field(proto.STRING, number=1) - - title = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + title = proto.Field(proto.STRING, number=1,) open_uri_action = proto.Field( proto.MESSAGE, number=2, message="Intent.Message.BasicCard.Button.OpenUriAction", ) - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - formatted_text = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + formatted_text = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.BasicCard.Button", ) @@ -566,11 +525,10 @@ class Suggestion(proto.Message): suggestion chip. """ - title = proto.Field(proto.STRING, number=1) + title = proto.Field(proto.STRING, number=1,) class Suggestions(proto.Message): r"""The collection of suggestions. - Attributes: suggestions (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.Suggestion]): Required. The list of suggested replies. @@ -593,13 +551,11 @@ class LinkOutSuggestion(proto.Message): when the user taps the suggestion chip. """ - destination_name = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) + destination_name = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) class ListSelect(proto.Message): r"""The card for presenting a list of options to select from. - Attributes: title (str): Optional. The overall title of the list. @@ -611,7 +567,6 @@ class ListSelect(proto.Message): class Item(proto.Message): r"""An item in the list. - Attributes: info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): Required. Additional information about this @@ -627,26 +582,20 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - title = proto.Field(proto.STRING, number=1) - + title = proto.Field(proto.STRING, number=1,) items = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.ListSelect.Item", ) - - subtitle = proto.Field(proto.STRING, number=3) + subtitle = proto.Field(proto.STRING, number=3,) class CarouselSelect(proto.Message): r"""The card for presenting a carousel of options to select from. - Attributes: items (Sequence[google.cloud.dialogflow_v2.types.Intent.Message.CarouselSelect.Item]): Required. Carousel items. @@ -654,7 +603,6 @@ class CarouselSelect(proto.Message): class Item(proto.Message): r"""An item in the carousel. - Attributes: info (google.cloud.dialogflow_v2.types.Intent.Message.SelectItemInfo): Required. Additional info about the option @@ -670,11 +618,8 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) @@ -696,13 +641,11 @@ class SelectItemInfo(proto.Message): used to trigger this item in dialog. """ - key = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + key = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class MediaContent(proto.Message): r"""The media content card for Actions on Google. - Attributes: media_type (google.cloud.dialogflow_v2.types.Intent.Message.MediaContent.ResponseMediaType): Optional. What type of media is the content @@ -718,7 +661,6 @@ class ResponseMediaType(proto.Enum): class ResponseMediaObject(proto.Message): r"""Response media object for media content card. - Attributes: name (str): Required. Name of media card. @@ -734,32 +676,27 @@ class ResponseMediaObject(proto.Message): Required. Url where the media is stored. """ - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) large_image = proto.Field( proto.MESSAGE, number=3, oneof="image", message="Intent.Message.Image", ) - icon = proto.Field( proto.MESSAGE, number=4, oneof="image", message="Intent.Message.Image", ) - - content_url = proto.Field(proto.STRING, number=5) + content_url = proto.Field(proto.STRING, number=5,) media_type = proto.Field( proto.ENUM, number=1, enum="Intent.Message.MediaContent.ResponseMediaType", ) - media_objects = proto.RepeatedField( proto.MESSAGE, number=2, @@ -794,7 +731,6 @@ class ImageDisplayOptions(proto.Enum): class BrowseCarouselCardItem(proto.Message): r"""Browsing carousel tile - Attributes: open_uri_action (google.cloud.dialogflow_v2.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): Required. Action to present to the user. @@ -814,7 +750,6 @@ class BrowseCarouselCardItem(proto.Message): class OpenUrlAction(proto.Message): r"""Actions on Google action to open a given url. - Attributes: url (str): Required. URL @@ -830,8 +765,7 @@ class UrlTypeHint(proto.Enum): AMP_ACTION = 1 AMP_CONTENT = 2 - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) url_type_hint = proto.Field( proto.ENUM, number=3, @@ -843,23 +777,18 @@ class UrlTypeHint(proto.Enum): number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - - footer = proto.Field(proto.STRING, number=5) + footer = proto.Field(proto.STRING, number=5,) items = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem", ) - image_display_options = proto.Field( proto.ENUM, number=2, @@ -868,7 +797,6 @@ class UrlTypeHint(proto.Enum): class TableCard(proto.Message): r"""Table card for Actions on Google. - Attributes: title (str): Required. Title of the card. @@ -886,22 +814,17 @@ class TableCard(proto.Message): Optional. List of buttons for the card. """ - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) image = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.Image", ) - column_properties = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.ColumnProperties", ) - rows = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.TableCardRow", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=6, message="Intent.Message.BasicCard.Button", ) @@ -925,8 +848,7 @@ class HorizontalAlignment(proto.Enum): CENTER = 2 TRAILING = 3 - header = proto.Field(proto.STRING, number=1) - + header = proto.Field(proto.STRING, number=1,) horizontal_alignment = proto.Field( proto.ENUM, number=2, @@ -949,8 +871,7 @@ class TableCardRow(proto.Message): cells = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.TableCardCell", ) - - divider_after = proto.Field(proto.BOOL, number=2) + divider_after = proto.Field(proto.BOOL, number=2,) class TableCardCell(proto.Message): r"""Cell of @@ -961,99 +882,84 @@ class TableCardCell(proto.Message): Required. Text in this cell. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) text = proto.Field( proto.MESSAGE, number=1, oneof="message", message="Intent.Message.Text", ) - image = proto.Field( proto.MESSAGE, number=2, oneof="message", message="Intent.Message.Image", ) - quick_replies = proto.Field( proto.MESSAGE, number=3, oneof="message", message="Intent.Message.QuickReplies", ) - card = proto.Field( proto.MESSAGE, number=4, oneof="message", message="Intent.Message.Card", ) - payload = proto.Field( - proto.MESSAGE, number=5, oneof="message", message=struct.Struct, + proto.MESSAGE, number=5, oneof="message", message=struct_pb2.Struct, ) - simple_responses = proto.Field( proto.MESSAGE, number=7, oneof="message", message="Intent.Message.SimpleResponses", ) - basic_card = proto.Field( proto.MESSAGE, number=8, oneof="message", message="Intent.Message.BasicCard", ) - suggestions = proto.Field( proto.MESSAGE, number=9, oneof="message", message="Intent.Message.Suggestions", ) - link_out_suggestion = proto.Field( proto.MESSAGE, number=10, oneof="message", message="Intent.Message.LinkOutSuggestion", ) - list_select = proto.Field( proto.MESSAGE, number=11, oneof="message", message="Intent.Message.ListSelect", ) - carousel_select = proto.Field( proto.MESSAGE, number=12, oneof="message", message="Intent.Message.CarouselSelect", ) - browse_carousel_card = proto.Field( proto.MESSAGE, number=22, oneof="message", message="Intent.Message.BrowseCarouselCard", ) - table_card = proto.Field( proto.MESSAGE, number=23, oneof="message", message="Intent.Message.TableCard", ) - media_content = proto.Field( proto.MESSAGE, number=24, oneof="message", message="Intent.Message.MediaContent", ) - platform = proto.Field(proto.ENUM, number=6, enum="Intent.Message.Platform",) class FollowupIntentInfo(proto.Message): r"""Represents a single followup intent in the chain. - Attributes: followup_intent_name (str): The unique identifier of the followup intent. Format: @@ -1063,54 +969,34 @@ class FollowupIntentInfo(proto.Message): Format: ``projects//agent/intents/``. """ - followup_intent_name = proto.Field(proto.STRING, number=1) - - parent_followup_intent_name = proto.Field(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + followup_intent_name = proto.Field(proto.STRING, number=1,) + parent_followup_intent_name = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) webhook_state = proto.Field(proto.ENUM, number=6, enum=WebhookState,) - - priority = proto.Field(proto.INT32, number=3) - - is_fallback = proto.Field(proto.BOOL, number=4) - - ml_disabled = proto.Field(proto.BOOL, number=19) - - live_agent_handoff = proto.Field(proto.BOOL, number=20) - - end_interaction = proto.Field(proto.BOOL, number=21) - - input_context_names = proto.RepeatedField(proto.STRING, number=7) - - events = proto.RepeatedField(proto.STRING, number=8) - + priority = proto.Field(proto.INT32, number=3,) + is_fallback = proto.Field(proto.BOOL, number=4,) + ml_disabled = proto.Field(proto.BOOL, number=19,) + live_agent_handoff = proto.Field(proto.BOOL, number=20,) + end_interaction = proto.Field(proto.BOOL, number=21,) + input_context_names = proto.RepeatedField(proto.STRING, number=7,) + events = proto.RepeatedField(proto.STRING, number=8,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=9, message=TrainingPhrase, ) - - action = proto.Field(proto.STRING, number=10) - + action = proto.Field(proto.STRING, number=10,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message=context.Context, ) - - reset_contexts = proto.Field(proto.BOOL, number=12) - + reset_contexts = proto.Field(proto.BOOL, number=12,) parameters = proto.RepeatedField(proto.MESSAGE, number=13, message=Parameter,) - messages = proto.RepeatedField(proto.MESSAGE, number=14, message=Message,) - default_response_platforms = proto.RepeatedField( proto.ENUM, number=15, enum=Message.Platform, ) - - root_followup_intent_name = proto.Field(proto.STRING, number=16) - - parent_followup_intent_name = proto.Field(proto.STRING, number=17) - + root_followup_intent_name = proto.Field(proto.STRING, number=16,) + parent_followup_intent_name = proto.Field(proto.STRING, number=17,) followup_intent_info = proto.RepeatedField( proto.MESSAGE, number=18, message=FollowupIntentInfo, ) @@ -1142,15 +1028,11 @@ class ListIntentsRequest(proto.Message): list 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=3, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) class ListIntentsResponse(proto.Message): @@ -1172,8 +1054,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): @@ -1195,10 +1076,8 @@ class GetIntentRequest(proto.Message): returned intent. """ - 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,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) @@ -1223,12 +1102,9 @@ class CreateIntentRequest(proto.Message): returned intent. """ - 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,) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1254,11 +1130,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, + ) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1274,12 +1149,11 @@ class DeleteIntentRequest(proto.Message): ``projects//agent/intents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateIntentsRequest(proto.Message): r""" - Attributes: parent (str): Required. The name of the agent to update or create intents @@ -1307,18 +1181,15 @@ class BatchUpdateIntentsRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - - intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch") - + parent = proto.Field(proto.STRING, number=1,) + intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch",) intent_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="intent_batch", message="IntentBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=6, enum="IntentView",) @@ -1347,14 +1218,12 @@ class BatchDeleteIntentsRequest(proto.Message): ``name`` must be filled in. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intents = proto.RepeatedField(proto.MESSAGE, number=2, message="Intent",) class IntentBatch(proto.Message): r"""This message is a wrapper around a collection of intents. - Attributes: intents (Sequence[google.cloud.dialogflow_v2.types.Intent]): A collection of intents. diff --git a/google/cloud/dialogflow_v2/types/knowledge_base.py b/google/cloud/dialogflow_v2/types/knowledge_base.py index 659be2ce6..c26345d64 100644 --- a/google/cloud/dialogflow_v2/types/knowledge_base.py +++ b/google/cloud/dialogflow_v2/types/knowledge_base.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( @@ -65,11 +62,9 @@ class KnowledgeBase(proto.Message): language code en-us applies. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=4,) class ListKnowledgeBasesRequest(proto.Message): @@ -88,11 +83,9 @@ class ListKnowledgeBasesRequest(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 ListKnowledgeBasesResponse(proto.Message): @@ -115,8 +108,7 @@ def raw_page(self): knowledge_bases = proto.RepeatedField( proto.MESSAGE, number=1, message="KnowledgeBase", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetKnowledgeBaseRequest(proto.Message): @@ -129,7 +121,7 @@ class GetKnowledgeBaseRequest(proto.Message): ``projects//locations//knowledgeBases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateKnowledgeBaseRequest(proto.Message): @@ -144,8 +136,7 @@ class CreateKnowledgeBaseRequest(proto.Message): Required. The knowledge base to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) knowledge_base = proto.Field(proto.MESSAGE, number=2, message="KnowledgeBase",) @@ -163,9 +154,8 @@ class DeleteKnowledgeBaseRequest(proto.Message): base are also deleted. """ - 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 UpdateKnowledgeBaseRequest(proto.Message): @@ -182,8 +172,9 @@ class UpdateKnowledgeBaseRequest(proto.Message): """ knowledge_base = proto.Field(proto.MESSAGE, number=1, message="KnowledgeBase",) - - 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, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/participant.py b/google/cloud/dialogflow_v2/types/participant.py index e965b4a09..7f5805c42 100644 --- a/google/cloud/dialogflow_v2/types/participant.py +++ b/google/cloud/dialogflow_v2/types/participant.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import session -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 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( @@ -83,16 +80,13 @@ class Role(proto.Enum): AUTOMATED_AGENT = 2 END_USER = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) role = proto.Field(proto.ENUM, number=2, enum=Role,) - - sip_recording_media_label = proto.Field(proto.STRING, number=6) + sip_recording_media_label = proto.Field(proto.STRING, number=6,) class Message(proto.Message): r"""Represents a message posted into a conversation. - Attributes: name (str): The unique identifier of the message. Format: @@ -115,18 +109,12 @@ class Message(proto.Message): Output only. The annotation for the message. """ - name = proto.Field(proto.STRING, number=1) - - content = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - participant = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + content = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + participant = proto.Field(proto.STRING, number=4,) participant_role = proto.Field(proto.ENUM, number=5, enum="Participant.Role",) - - create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) message_annotation = proto.Field( proto.MESSAGE, number=7, message="MessageAnnotation", ) @@ -145,8 +133,7 @@ class CreateParticipantRequest(proto.Message): Required. The participant to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) participant = proto.Field(proto.MESSAGE, number=2, message="Participant",) @@ -160,7 +147,7 @@ class GetParticipantRequest(proto.Message): ``projects//locations//conversations//participants/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListParticipantsRequest(proto.Message): @@ -181,11 +168,9 @@ class ListParticipantsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListParticipantsResponse(proto.Message): @@ -206,8 +191,7 @@ def raw_page(self): return self participants = proto.RepeatedField(proto.MESSAGE, number=1, message="Participant",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateParticipantRequest(proto.Message): @@ -223,8 +207,9 @@ class UpdateParticipantRequest(proto.Message): """ participant = proto.Field(proto.MESSAGE, number=1, message="Participant",) - - 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 AnalyzeContentRequest(proto.Message): @@ -256,25 +241,20 @@ class AnalyzeContentRequest(proto.Message): only idempotent if a ``request_id`` is provided. """ - participant = proto.Field(proto.STRING, number=1) - + participant = proto.Field(proto.STRING, number=1,) text_input = proto.Field( proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) - reply_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) - query_params = proto.Field( proto.MESSAGE, number=9, message=session.QueryParameters, ) - - request_id = proto.Field(proto.STRING, number=11) + request_id = proto.Field(proto.STRING, number=11,) class DtmfParameters(proto.Message): @@ -287,7 +267,7 @@ class DtmfParameters(proto.Message): in the next request. """ - accepts_dtmf_input = proto.Field(proto.BOOL, number=1) + accepts_dtmf_input = proto.Field(proto.BOOL, number=1,) class AnalyzeContentResponse(proto.Message): @@ -337,24 +317,18 @@ class AnalyzeContentResponse(proto.Message): Indicates the parameters of DTMF. """ - reply_text = proto.Field(proto.STRING, number=1) - + reply_text = proto.Field(proto.STRING, number=1,) reply_audio = proto.Field(proto.MESSAGE, number=2, message="OutputAudio",) - automated_agent_reply = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentReply", ) - message = proto.Field(proto.MESSAGE, number=5, message="Message",) - human_agent_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=6, message="SuggestionResult", ) - end_user_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=7, message="SuggestionResult", ) - dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) @@ -381,11 +355,9 @@ class SuggestArticlesRequest(proto.Message): 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestArticlesResponse(proto.Message): @@ -414,10 +386,8 @@ class SuggestArticlesResponse(proto.Message): article_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="ArticleAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersRequest(proto.Message): @@ -442,11 +412,9 @@ class SuggestFaqAnswersRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersResponse(proto.Message): @@ -472,10 +440,8 @@ class SuggestFaqAnswersResponse(proto.Message): """ faq_answers = proto.RepeatedField(proto.MESSAGE, number=1, message="FaqAnswer",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class OutputAudio(proto.Message): @@ -493,13 +459,11 @@ class OutputAudio(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class AutomatedAgentReply(proto.Message): r"""Represents a response from an automated agent. - Attributes: detect_intent_response (google.cloud.dialogflow_v2.types.DetectIntentResponse): Response of the Dialogflow @@ -514,7 +478,6 @@ class AutomatedAgentReply(proto.Message): class ArticleAnswer(proto.Message): r"""Represents article answer. - Attributes: title (str): The article title. @@ -537,22 +500,16 @@ class ArticleAnswer(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - confidence = proto.Field(proto.FLOAT, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents answer from "frequently asked questions". - Attributes: answer (str): The piece of text from the ``source`` knowledge base @@ -577,17 +534,12 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class SuggestionResult(proto.Message): @@ -610,16 +562,14 @@ class SuggestionResult(proto.Message): """ error = proto.Field( - proto.MESSAGE, number=1, oneof="suggestion_response", message=status.Status, + proto.MESSAGE, number=1, oneof="suggestion_response", message=status_pb2.Status, ) - suggest_articles_response = proto.Field( proto.MESSAGE, number=2, oneof="suggestion_response", message="SuggestArticlesResponse", ) - suggest_faq_answers_response = proto.Field( proto.MESSAGE, number=3, @@ -658,16 +608,13 @@ class AnnotatedMessagePart(proto.Message): """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct.Value,) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Value,) class MessageAnnotation(proto.Message): r"""Represents the result of annotation for the message. - Attributes: parts (Sequence[google.cloud.dialogflow_v2.types.AnnotatedMessagePart]): The collection of annotated message parts ordered by their @@ -681,8 +628,7 @@ class MessageAnnotation(proto.Message): parts = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotatedMessagePart", ) - - contain_entities = proto.Field(proto.BOOL, number=2) + contain_entities = proto.Field(proto.BOOL, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/session.py b/google/cloud/dialogflow_v2/types/session.py index f7bebda23..e48ead899 100644 --- a/google/cloud/dialogflow_v2/types/session.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.types import audio_config as gcd_audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent as gcd_intent from google.cloud.dialogflow_v2.types import session_entity_type -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.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 field_mask_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( @@ -51,7 +48,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. @@ -108,26 +104,20 @@ class DetectIntentRequest(proto.Message): minute of speech audio data. """ - 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=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=5) + input_audio = proto.Field(proto.BYTES, number=5,) class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): The unique identifier of the response. It can @@ -156,14 +146,10 @@ 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",) - - webhook_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=4) - + webhook_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -171,7 +157,6 @@ class DetectIntentResponse(proto.Message): class QueryParameters(proto.Message): r"""Represents the parameters of the conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -218,25 +203,18 @@ class QueryParameters(proto.Message): Since", "If-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,) contexts = proto.RepeatedField(proto.MESSAGE, number=3, message=context.Context,) - - reset_contexts = proto.Field(proto.BOOL, number=4) - + reset_contexts = proto.Field(proto.BOOL, number=4,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=5, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - + payload = proto.Field(proto.MESSAGE, number=6, message=struct_pb2.Struct,) sentiment_analysis_request_config = proto.Field( proto.MESSAGE, number=10, message="SentimentAnalysisRequestConfig", ) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14,) class QueryInput(proto.Message): @@ -264,9 +242,7 @@ class QueryInput(proto.Message): oneof="input", message=gcd_audio_config.InputAudioConfig, ) - text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - event = proto.Field(proto.MESSAGE, number=3, oneof="input", message="EventInput",) @@ -386,38 +362,24 @@ class QueryResult(proto.Message): request. """ - query_text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=15) - - speech_recognition_confidence = proto.Field(proto.FLOAT, number=2) - - action = proto.Field(proto.STRING, number=3) - - parameters = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - all_required_params_present = proto.Field(proto.BOOL, number=5) - - fulfillment_text = proto.Field(proto.STRING, number=6) - + query_text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=15,) + speech_recognition_confidence = proto.Field(proto.FLOAT, number=2,) + action = proto.Field(proto.STRING, number=3,) + parameters = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + all_required_params_present = proto.Field(proto.BOOL, number=5,) + fulfillment_text = proto.Field(proto.STRING, number=6,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_intent.Intent.Message, ) - - webhook_source = proto.Field(proto.STRING, number=8) - - webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) - + webhook_source = proto.Field(proto.STRING, number=8,) + webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=10, message=context.Context, ) - intent = proto.Field(proto.MESSAGE, number=11, message=gcd_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=12) - - diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct.Struct,) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=12,) + diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) @@ -527,23 +489,17 @@ class StreamingDetectIntentRequest(proto.Message): exceed 1 minute. """ - 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",) - - single_utterance = proto.Field(proto.BOOL, number=4) - + single_utterance = proto.Field(proto.BOOL, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=6) + input_audio = proto.Field(proto.BYTES, number=6,) class StreamingDetectIntentResponse(proto.Message): @@ -590,18 +546,13 @@ class StreamingDetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) recognition_result = proto.Field( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - query_result = proto.Field(proto.MESSAGE, number=3, message="QueryResult",) - - webhook_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=5) - + webhook_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=5,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -681,23 +632,19 @@ 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) - + transcript = proto.Field(proto.STRING, number=2,) + is_final = proto.Field(proto.BOOL, number=3,) + confidence = proto.Field(proto.FLOAT, number=4,) speech_word_info = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_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 TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -712,9 +659,8 @@ class TextInput(proto.Message): specify the same language. """ - text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class EventInput(proto.Message): @@ -756,16 +702,13 @@ class EventInput(proto.Message): specify the same language. """ - name = proto.Field(proto.STRING, number=1) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - language_code = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + language_code = proto.Field(proto.STRING, number=3,) class SentimentAnalysisRequestConfig(proto.Message): r"""Configures the types of sentiment analysis to perform. - Attributes: analyze_query_text_sentiment (bool): Instructs the service to perform sentiment analysis on @@ -773,7 +716,7 @@ class SentimentAnalysisRequestConfig(proto.Message): performed on ``query_text``. """ - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1,) class SentimentAnalysisResult(proto.Message): @@ -814,9 +757,8 @@ class Sentiment(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/dialogflow_v2/types/session_entity_type.py b/google/cloud/dialogflow_v2/types/session_entity_type.py index 978eb6056..619b7a8c9 100644 --- a/google/cloud/dialogflow_v2/types/session_entity_type.py +++ b/google/cloud/dialogflow_v2/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.dialogflow_v2.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( @@ -76,10 +73,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=2, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=3, message=entity_type.EntityType.Entity, ) @@ -107,11 +102,9 @@ class ListSessionEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + 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): @@ -155,7 +147,7 @@ class GetSessionEntityTypeRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -175,8 +167,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", ) @@ -197,8 +188,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): @@ -216,7 +208,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/validation_result.py b/google/cloud/dialogflow_v2/types/validation_result.py index a1d181327..2e3ae1ea5 100644 --- a/google/cloud/dialogflow_v2/types/validation_result.py +++ b/google/cloud/dialogflow_v2/types/validation_result.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 ValidationError(proto.Message): r"""Represents a single validation error. - Attributes: severity (google.cloud.dialogflow_v2.types.ValidationError.Severity): The severity of the error. @@ -63,15 +60,12 @@ class Severity(proto.Enum): CRITICAL = 4 severity = proto.Field(proto.ENUM, number=1, enum=Severity,) - - entries = proto.RepeatedField(proto.STRING, number=3) - - error_message = proto.Field(proto.STRING, number=4) + entries = proto.RepeatedField(proto.STRING, number=3,) + error_message = proto.Field(proto.STRING, number=4,) class ValidationResult(proto.Message): r"""Represents the output of agent validation. - Attributes: validation_errors (Sequence[google.cloud.dialogflow_v2.types.ValidationError]): Contains all validation errors. diff --git a/google/cloud/dialogflow_v2/types/version.py b/google/cloud/dialogflow_v2/types/version.py new file mode 100644 index 000000000..6400e0445 --- /dev/null +++ b/google/cloud/dialogflow_v2/types/version.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={ + "Version", + "ListVersionsRequest", + "ListVersionsResponse", + "GetVersionRequest", + "CreateVersionRequest", + "UpdateVersionRequest", + "DeleteVersionRequest", + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + version_number = proto.Field(proto.INT32, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.ENUM, number=6, enum=VersionStatus,) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField(proto.MESSAGE, number=1, message="Version",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to create. + """ + + parent = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.MESSAGE, number=2, message="Version",) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field(proto.MESSAGE, number=1, message="Version",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2/types/webhook.py b/google/cloud/dialogflow_v2/types/webhook.py index e7776734c..8c96b6676 100644 --- a/google/cloud/dialogflow_v2/types/webhook.py +++ b/google/cloud/dialogflow_v2/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,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import session as gcd_session from google.cloud.dialogflow_v2.types import session_entity_type -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -33,7 +30,6 @@ class WebhookRequest(proto.Message): r"""The request message for a webhook call. - Attributes: session (str): The unique identifier of detectIntent request session. Can @@ -53,14 +49,11 @@ class WebhookRequest(proto.Message): passed to ``[Streaming]DetectIntent`` call. """ - session = proto.Field(proto.STRING, number=4) - - response_id = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=4,) + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field( proto.MESSAGE, number=2, message=gcd_session.QueryResult, ) - original_detect_intent_request = proto.Field( proto.MESSAGE, number=3, message="OriginalDetectIntentRequest", ) @@ -136,24 +129,18 @@ class WebhookResponse(proto.Message): management methods. """ - fulfillment_text = proto.Field(proto.STRING, number=1) - + fulfillment_text = proto.Field(proto.STRING, number=1,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=intent.Intent.Message, ) - - source = proto.Field(proto.STRING, number=3) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + source = proto.Field(proto.STRING, number=3,) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=5, message=context.Context, ) - followup_event_input = proto.Field( proto.MESSAGE, number=6, message=gcd_session.EventInput, ) - session_entity_types = proto.RepeatedField( proto.MESSAGE, number=10, message=session_entity_type.SessionEntityType, ) @@ -193,11 +180,9 @@ class OriginalDetectIntentRequest(proto.Message): Essentials Edition agents. """ - source = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - payload = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + source = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + payload = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/__init__.py b/google/cloud/dialogflow_v2beta1/__init__.py index 52d53f6ed..dabecdb9f 100644 --- a/google/cloud/dialogflow_v2beta1/__init__.py +++ b/google/cloud/dialogflow_v2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,36 @@ # from .services.agents import AgentsClient +from .services.agents import AgentsAsyncClient from .services.answer_records import AnswerRecordsClient +from .services.answer_records import AnswerRecordsAsyncClient from .services.contexts import ContextsClient +from .services.contexts import ContextsAsyncClient from .services.conversation_profiles import ConversationProfilesClient +from .services.conversation_profiles import ConversationProfilesAsyncClient from .services.conversations import ConversationsClient +from .services.conversations import ConversationsAsyncClient from .services.documents import DocumentsClient +from .services.documents import DocumentsAsyncClient from .services.entity_types import EntityTypesClient +from .services.entity_types import EntityTypesAsyncClient from .services.environments import EnvironmentsClient +from .services.environments import EnvironmentsAsyncClient +from .services.fulfillments import FulfillmentsClient +from .services.fulfillments import FulfillmentsAsyncClient from .services.intents import IntentsClient +from .services.intents import IntentsAsyncClient from .services.knowledge_bases import KnowledgeBasesClient +from .services.knowledge_bases import KnowledgeBasesAsyncClient from .services.participants import ParticipantsClient +from .services.participants import ParticipantsAsyncClient 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.versions import VersionsClient +from .services.versions import VersionsAsyncClient + from .types.agent import Agent from .types.agent import DeleteAgentRequest from .types.agent import ExportAgentRequest @@ -49,19 +66,19 @@ from .types.answer_record import ListAnswerRecordsRequest from .types.answer_record import ListAnswerRecordsResponse from .types.answer_record import UpdateAnswerRecordRequest -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 SpeechContext -from .types.audio_config import SpeechModelVariant from .types.audio_config import SpeechToTextConfig from .types.audio_config import SpeechWordInfo -from .types.audio_config import SsmlVoiceGender from .types.audio_config import SynthesizeSpeechConfig -from .types.audio_config import TelephonyDtmf from .types.audio_config import TelephonyDtmfEvents 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.audio_config import TelephonyDtmf from .types.context import Context from .types.context import CreateContextRequest from .types.context import DeleteAllContextsRequest @@ -99,9 +116,9 @@ from .types.document import DeleteDocumentRequest from .types.document import Document from .types.document import GetDocumentRequest -from .types.document import ImportDocumentTemplate from .types.document import ImportDocumentsRequest from .types.document import ImportDocumentsResponse +from .types.document import ImportDocumentTemplate from .types.document import KnowledgeOperationMetadata from .types.document import ListDocumentsRequest from .types.document import ListDocumentsResponse @@ -121,9 +138,19 @@ from .types.entity_type import ListEntityTypesRequest from .types.entity_type import ListEntityTypesResponse from .types.entity_type import UpdateEntityTypeRequest +from .types.environment import CreateEnvironmentRequest +from .types.environment import DeleteEnvironmentRequest from .types.environment import Environment +from .types.environment import EnvironmentHistory +from .types.environment import GetEnvironmentHistoryRequest +from .types.environment import GetEnvironmentRequest from .types.environment import ListEnvironmentsRequest from .types.environment import ListEnvironmentsResponse +from .types.environment import TextToSpeechSettings +from .types.environment import UpdateEnvironmentRequest +from .types.fulfillment import Fulfillment +from .types.fulfillment import GetFulfillmentRequest +from .types.fulfillment import UpdateFulfillmentRequest from .types.gcs import GcsSource from .types.gcs import GcsSources from .types.human_agent_assistant_event import HumanAgentAssistantEvent @@ -135,10 +162,10 @@ from .types.intent import GetIntentRequest from .types.intent import Intent from .types.intent import IntentBatch -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.knowledge_base import CreateKnowledgeBaseRequest from .types.knowledge_base import DeleteKnowledgeBaseRequest from .types.knowledge_base import GetKnowledgeBaseRequest @@ -171,11 +198,11 @@ from .types.participant import SuggestArticlesResponse from .types.participant import SuggestFaqAnswersRequest from .types.participant import SuggestFaqAnswersResponse -from .types.participant import SuggestSmartRepliesRequest -from .types.participant import SuggestSmartRepliesResponse from .types.participant import Suggestion from .types.participant import SuggestionFeature from .types.participant import SuggestionResult +from .types.participant import SuggestSmartRepliesRequest +from .types.participant import SuggestSmartRepliesResponse from .types.participant import UpdateParticipantRequest from .types.session import DetectIntentRequest from .types.session import DetectIntentResponse @@ -200,11 +227,17 @@ from .types.session_entity_type import UpdateSessionEntityTypeRequest from .types.validation_result import ValidationError from .types.validation_result import ValidationResult +from .types.version import CreateVersionRequest +from .types.version import DeleteVersionRequest +from .types.version import GetVersionRequest +from .types.version import ListVersionsRequest +from .types.version import ListVersionsResponse +from .types.version import UpdateVersionRequest +from .types.version import Version from .types.webhook import OriginalDetectIntentRequest from .types.webhook import WebhookRequest from .types.webhook import WebhookResponse - __all__ = ( "Agent", "AgentAssistantFeedback", @@ -247,20 +280,24 @@ "CreateConversationRequest", "CreateDocumentRequest", "CreateEntityTypeRequest", + "CreateEnvironmentRequest", "CreateIntentRequest", "CreateKnowledgeBaseRequest", "CreateMessageRequest", "CreateParticipantRequest", "CreateSessionEntityTypeRequest", + "CreateVersionRequest", "DeleteAgentRequest", "DeleteAllContextsRequest", "DeleteContextRequest", "DeleteConversationProfileRequest", "DeleteDocumentRequest", "DeleteEntityTypeRequest", + "DeleteEnvironmentRequest", "DeleteIntentRequest", "DeleteKnowledgeBaseRequest", "DeleteSessionEntityTypeRequest", + "DeleteVersionRequest", "DetectIntentRequest", "DetectIntentResponse", "Document", @@ -270,11 +307,14 @@ "EntityTypeBatch", "EntityTypesClient", "Environment", + "EnvironmentHistory", "EnvironmentsClient", "EventInput", "ExportAgentRequest", "ExportAgentResponse", "FaqAnswer", + "Fulfillment", + "FulfillmentsClient", "GcsSource", "GcsSources", "GetAgentRequest", @@ -284,11 +324,15 @@ "GetConversationRequest", "GetDocumentRequest", "GetEntityTypeRequest", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", + "GetFulfillmentRequest", "GetIntentRequest", "GetKnowledgeBaseRequest", "GetParticipantRequest", "GetSessionEntityTypeRequest", "GetValidationResultRequest", + "GetVersionRequest", "HumanAgentAssistantConfig", "HumanAgentAssistantEvent", "HumanAgentHandoffConfig", @@ -303,6 +347,7 @@ "IntentsClient", "KnowledgeAnswers", "KnowledgeBase", + "KnowledgeBasesClient", "KnowledgeOperationMetadata", "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", @@ -330,6 +375,8 @@ "ListSessionEntityTypesResponse", "ListSuggestionsRequest", "ListSuggestionsResponse", + "ListVersionsRequest", + "ListVersionsResponse", "LoggingConfig", "Message", "MessageAnnotation", @@ -378,20 +425,25 @@ "TelephonyDtmf", "TelephonyDtmfEvents", "TextInput", + "TextToSpeechSettings", "TrainAgentRequest", "UpdateAnswerRecordRequest", "UpdateContextRequest", "UpdateConversationProfileRequest", "UpdateDocumentRequest", "UpdateEntityTypeRequest", + "UpdateEnvironmentRequest", + "UpdateFulfillmentRequest", "UpdateIntentRequest", "UpdateKnowledgeBaseRequest", "UpdateParticipantRequest", "UpdateSessionEntityTypeRequest", + "UpdateVersionRequest", "ValidationError", "ValidationResult", + "Version", + "VersionsClient", "VoiceSelectionParams", "WebhookRequest", "WebhookResponse", - "KnowledgeBasesClient", ) diff --git a/google/cloud/dialogflow_v2beta1/gapic_metadata.json b/google/cloud/dialogflow_v2beta1/gapic_metadata.json new file mode 100644 index 000000000..ed94b0a54 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/gapic_metadata.json @@ -0,0 +1,1099 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.dialogflow_v2beta1", + "protoPackage": "google.cloud.dialogflow.v2beta1", + "schema": "1.0", + "services": { + "Agents": { + "clients": { + "grpc": { + "libraryClient": "AgentsClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentsAsyncClient", + "rpcs": { + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "ExportAgent": { + "methods": [ + "export_agent" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetValidationResult": { + "methods": [ + "get_validation_result" + ] + }, + "ImportAgent": { + "methods": [ + "import_agent" + ] + }, + "RestoreAgent": { + "methods": [ + "restore_agent" + ] + }, + "SearchAgents": { + "methods": [ + "search_agents" + ] + }, + "SetAgent": { + "methods": [ + "set_agent" + ] + }, + "TrainAgent": { + "methods": [ + "train_agent" + ] + } + } + } + } + }, + "AnswerRecords": { + "clients": { + "grpc": { + "libraryClient": "AnswerRecordsClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnswerRecordsAsyncClient", + "rpcs": { + "GetAnswerRecord": { + "methods": [ + "get_answer_record" + ] + }, + "ListAnswerRecords": { + "methods": [ + "list_answer_records" + ] + }, + "UpdateAnswerRecord": { + "methods": [ + "update_answer_record" + ] + } + } + } + } + }, + "Contexts": { + "clients": { + "grpc": { + "libraryClient": "ContextsClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ContextsAsyncClient", + "rpcs": { + "CreateContext": { + "methods": [ + "create_context" + ] + }, + "DeleteAllContexts": { + "methods": [ + "delete_all_contexts" + ] + }, + "DeleteContext": { + "methods": [ + "delete_context" + ] + }, + "GetContext": { + "methods": [ + "get_context" + ] + }, + "ListContexts": { + "methods": [ + "list_contexts" + ] + }, + "UpdateContext": { + "methods": [ + "update_context" + ] + } + } + } + } + }, + "ConversationProfiles": { + "clients": { + "grpc": { + "libraryClient": "ConversationProfilesClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationProfilesAsyncClient", + "rpcs": { + "CreateConversationProfile": { + "methods": [ + "create_conversation_profile" + ] + }, + "DeleteConversationProfile": { + "methods": [ + "delete_conversation_profile" + ] + }, + "GetConversationProfile": { + "methods": [ + "get_conversation_profile" + ] + }, + "ListConversationProfiles": { + "methods": [ + "list_conversation_profiles" + ] + }, + "UpdateConversationProfile": { + "methods": [ + "update_conversation_profile" + ] + } + } + } + } + }, + "Conversations": { + "clients": { + "grpc": { + "libraryClient": "ConversationsClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationsAsyncClient", + "rpcs": { + "BatchCreateMessages": { + "methods": [ + "batch_create_messages" + ] + }, + "CompleteConversation": { + "methods": [ + "complete_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListMessages": { + "methods": [ + "list_messages" + ] + } + } + } + } + }, + "Documents": { + "clients": { + "grpc": { + "libraryClient": "DocumentsClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentsAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "ReloadDocument": { + "methods": [ + "reload_document" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EntityTypes": { + "clients": { + "grpc": { + "libraryClient": "EntityTypesClient", + "rpcs": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "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": { + "BatchCreateEntities": { + "methods": [ + "batch_create_entities" + ] + }, + "BatchDeleteEntities": { + "methods": [ + "batch_delete_entities" + ] + }, + "BatchDeleteEntityTypes": { + "methods": [ + "batch_delete_entity_types" + ] + }, + "BatchUpdateEntities": { + "methods": [ + "batch_update_entities" + ] + }, + "BatchUpdateEntityTypes": { + "methods": [ + "batch_update_entity_types" + ] + }, + "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" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "GetEnvironmentHistory": { + "methods": [ + "get_environment_history" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "Fulfillments": { + "clients": { + "grpc": { + "libraryClient": "FulfillmentsClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "FulfillmentsAsyncClient", + "rpcs": { + "GetFulfillment": { + "methods": [ + "get_fulfillment" + ] + }, + "UpdateFulfillment": { + "methods": [ + "update_fulfillment" + ] + } + } + } + } + }, + "Intents": { + "clients": { + "grpc": { + "libraryClient": "IntentsClient", + "rpcs": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "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": { + "BatchDeleteIntents": { + "methods": [ + "batch_delete_intents" + ] + }, + "BatchUpdateIntents": { + "methods": [ + "batch_update_intents" + ] + }, + "CreateIntent": { + "methods": [ + "create_intent" + ] + }, + "DeleteIntent": { + "methods": [ + "delete_intent" + ] + }, + "GetIntent": { + "methods": [ + "get_intent" + ] + }, + "ListIntents": { + "methods": [ + "list_intents" + ] + }, + "UpdateIntent": { + "methods": [ + "update_intent" + ] + } + } + } + } + }, + "KnowledgeBases": { + "clients": { + "grpc": { + "libraryClient": "KnowledgeBasesClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KnowledgeBasesAsyncClient", + "rpcs": { + "CreateKnowledgeBase": { + "methods": [ + "create_knowledge_base" + ] + }, + "DeleteKnowledgeBase": { + "methods": [ + "delete_knowledge_base" + ] + }, + "GetKnowledgeBase": { + "methods": [ + "get_knowledge_base" + ] + }, + "ListKnowledgeBases": { + "methods": [ + "list_knowledge_bases" + ] + }, + "UpdateKnowledgeBase": { + "methods": [ + "update_knowledge_base" + ] + } + } + } + } + }, + "Participants": { + "clients": { + "grpc": { + "libraryClient": "ParticipantsClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ParticipantsAsyncClient", + "rpcs": { + "AnalyzeContent": { + "methods": [ + "analyze_content" + ] + }, + "CompileSuggestion": { + "methods": [ + "compile_suggestion" + ] + }, + "CreateParticipant": { + "methods": [ + "create_participant" + ] + }, + "GetParticipant": { + "methods": [ + "get_participant" + ] + }, + "ListParticipants": { + "methods": [ + "list_participants" + ] + }, + "ListSuggestions": { + "methods": [ + "list_suggestions" + ] + }, + "SuggestArticles": { + "methods": [ + "suggest_articles" + ] + }, + "SuggestFaqAnswers": { + "methods": [ + "suggest_faq_answers" + ] + }, + "SuggestSmartReplies": { + "methods": [ + "suggest_smart_replies" + ] + }, + "UpdateParticipant": { + "methods": [ + "update_participant" + ] + } + } + } + } + }, + "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" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionsAsyncClient", + "rpcs": { + "DetectIntent": { + "methods": [ + "detect_intent" + ] + }, + "StreamingDetectIntent": { + "methods": [ + "streaming_detect_intent" + ] + } + } + } + } + }, + "Versions": { + "clients": { + "grpc": { + "libraryClient": "VersionsClient", + "rpcs": { + "CreateVersion": { + "methods": [ + "create_version" + ] + }, + "DeleteVersion": { + "methods": [ + "delete_version" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "ListVersions": { + "methods": [ + "list_versions" + ] + }, + "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" + ] + }, + "UpdateVersion": { + "methods": [ + "update_version" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/dialogflow_v2beta1/services/__init__.py b/google/cloud/dialogflow_v2beta1/services/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/google/cloud/dialogflow_v2beta1/services/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/agents/__init__.py b/google/cloud/dialogflow_v2beta1/services/agents/__init__.py index 4bcbd7ac8..0501fa947 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/agents/async_client.py b/google/cloud/dialogflow_v2beta1/services/agents/async_client.py index 3ec1c0c33..c4bb88047 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_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 @@ -54,23 +51,18 @@ class AgentsAsyncClient: agent_path = staticmethod(AgentsClient.agent_path) parse_agent_path = staticmethod(AgentsClient.parse_agent_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) @@ -122,7 +114,7 @@ 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, @@ -159,7 +151,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AgentsClient( credentials=credentials, transport=transport, @@ -190,7 +181,6 @@ async def get_agent( 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 +216,6 @@ async def get_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -270,7 +259,6 @@ async def set_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. @@ -306,7 +294,6 @@ async def set_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -355,7 +342,6 @@ async def delete_agent( 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. @@ -376,7 +362,6 @@ async def delete_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -427,7 +412,6 @@ async def search_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. @@ -457,7 +441,6 @@ async def search_agents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -513,7 +496,6 @@ async def train_agent( 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. @@ -553,7 +535,6 @@ async def train_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -578,8 +559,8 @@ async def train_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. @@ -611,7 +592,6 @@ async def export_agent( 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,7 +622,6 @@ async def export_agent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -668,7 +647,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. @@ -705,7 +684,6 @@ async def import_agent( request (:class:`google.cloud.dialogflow_v2beta1.types.ImportAgentRequest`): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -732,7 +710,6 @@ async def import_agent( """ # Create or coerce a protobuf request object. - request = agent.ImportAgentRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -756,8 +733,8 @@ async def import_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. @@ -792,7 +769,6 @@ async def restore_agent( request (:class:`google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest`): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -819,7 +795,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, @@ -843,8 +818,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. @@ -866,7 +841,6 @@ async def get_validation_result( request (:class:`google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest`): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -880,7 +854,6 @@ async def get_validation_result( """ # Create or coerce a protobuf request object. - request = agent.GetValidationResultRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2beta1/services/agents/client.py b/google/cloud/dialogflow_v2beta1/services/agents/client.py index 656adc907..9a8b663db 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/client.py +++ b/google/cloud/dialogflow_v2beta1/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,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore - +from google.protobuf import empty_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 @@ -234,7 +231,7 @@ 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, @@ -367,7 +364,6 @@ def get_agent( 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. @@ -405,10 +401,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 parent is not None: request.parent = parent @@ -448,7 +442,6 @@ def set_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. @@ -486,10 +479,8 @@ def set_agent( # there are no flattened fields. if not isinstance(request, gcd_agent.SetAgentRequest): request = gcd_agent.SetAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if agent is not None: request.agent = agent @@ -534,7 +525,6 @@ def delete_agent( 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. @@ -557,10 +547,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 parent is not None: request.parent = parent @@ -607,7 +595,6 @@ def search_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. @@ -639,10 +626,8 @@ def search_agents( # there are no flattened fields. if not isinstance(request, agent.SearchAgentsRequest): request = agent.SearchAgentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -694,7 +679,6 @@ def train_agent( 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. @@ -736,10 +720,8 @@ def train_agent( # there are no flattened fields. if not isinstance(request, agent.TrainAgentRequest): request = agent.TrainAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -760,8 +742,8 @@ def train_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. @@ -793,7 +775,6 @@ def export_agent( 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. @@ -826,10 +807,8 @@ def export_agent( # there are no flattened fields. if not isinstance(request, agent.ExportAgentRequest): request = agent.ExportAgentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -851,7 +830,7 @@ def export_agent( response, self._transport.operations_client, agent.ExportAgentResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -888,7 +867,6 @@ def import_agent( request (google.cloud.dialogflow_v2beta1.types.ImportAgentRequest): The request object. The request message for [Agents.ImportAgent][google.cloud.dialogflow.v2beta1.Agents.ImportAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -915,7 +893,6 @@ def import_agent( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.ImportAgentRequest. # There's no risk of modifying the input as we've already verified @@ -940,8 +917,8 @@ def import_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. @@ -976,7 +953,6 @@ def restore_agent( request (google.cloud.dialogflow_v2beta1.types.RestoreAgentRequest): The request object. The request message for [Agents.RestoreAgent][google.cloud.dialogflow.v2beta1.Agents.RestoreAgent]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1003,7 +979,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 @@ -1028,8 +1003,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. @@ -1051,7 +1026,6 @@ def get_validation_result( request (google.cloud.dialogflow_v2beta1.types.GetValidationResultRequest): The request object. The request message for [Agents.GetValidationResult][google.cloud.dialogflow.v2beta1.Agents.GetValidationResult]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1065,7 +1039,6 @@ def get_validation_result( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a agent.GetValidationResultRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2beta1/services/agents/pagers.py b/google/cloud/dialogflow_v2beta1/services/agents/pagers.py index e3c037634..781de58e9 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/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, diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py index dfed91927..ceadcd3aa 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/agents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py index 7e10d2019..4dfac8794 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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,24 +13,24 @@ # 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.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -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( @@ -42,6 +41,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.""" @@ -51,21 +61,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 @@ -74,7 +87,7 @@ 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): @@ -88,29 +101,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -153,85 +213,78 @@ def operations_client(self) -> operations_v1.OperationsClient: @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 set_agent( self, - ) -> typing.Callable[ - [gcd_agent.SetAgentRequest], - typing.Union[gcd_agent.Agent, typing.Awaitable[gcd_agent.Agent]], + ) -> Callable[ + [gcd_agent.SetAgentRequest], Union[gcd_agent.Agent, Awaitable[gcd_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 search_agents( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.SearchAgentsRequest], - typing.Union[ - agent.SearchAgentsResponse, typing.Awaitable[agent.SearchAgentsResponse] - ], + Union[agent.SearchAgentsResponse, Awaitable[agent.SearchAgentsResponse]], ]: raise NotImplementedError() @property def train_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.TrainAgentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: 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 import_agent( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.ImportAgentRequest], - 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 get_validation_result( self, - ) -> typing.Callable[ + ) -> Callable[ [agent.GetValidationResultRequest], - typing.Union[ + Union[ validation_result.ValidationResult, - typing.Awaitable[validation_result.ValidationResult], + Awaitable[validation_result.ValidationResult], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py index 675d3ac95..79926da48 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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,15 +13,14 @@ # 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 @@ -30,9 +28,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -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 @@ -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 @@ -181,7 +179,7 @@ def __init__( 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,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, ) @@ -291,7 +291,7 @@ def set_agent(self) -> Callable[[gcd_agent.SetAgentRequest], gcd_agent.Agent]: return self._stubs["set_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. @@ -310,7 +310,7 @@ def delete_agent(self) -> Callable[[agent.DeleteAgentRequest], empty.Empty]: self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -346,7 +346,9 @@ def search_agents( return self._stubs["search_agents"] @property - def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operation]: + def train_agent( + self, + ) -> Callable[[agent.TrainAgentRequest], operations_pb2.Operation]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -368,14 +370,14 @@ def train_agent(self) -> Callable[[agent.TrainAgentRequest], operations.Operatio self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_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 ZIP file. @@ -397,14 +399,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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 import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], operations.Operation]: + ) -> Callable[[agent.ImportAgentRequest], operations_pb2.Operation]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -440,14 +442,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_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 ZIP file. @@ -481,7 +483,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py index ad50f2638..f1e6cd4d1 100644 --- a/google/cloud/dialogflow_v2beta1/services/agents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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,16 +13,15 @@ # 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 @@ -31,9 +29,8 @@ from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result -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 @@ -59,7 +56,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, @@ -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 @@ -173,7 +173,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -301,7 +300,7 @@ def set_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. @@ -320,7 +319,7 @@ def delete_agent( self._stubs["delete_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/DeleteAgent", request_serializer=agent.DeleteAgentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_agent"] @@ -358,7 +357,7 @@ def search_agents( @property def train_agent( self, - ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.TrainAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the train agent method over gRPC. Trains the specified agent. @@ -380,14 +379,14 @@ def train_agent( self._stubs["train_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/TrainAgent", request_serializer=agent.TrainAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["train_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 ZIP file. @@ -409,14 +408,14 @@ def export_agent( self._stubs["export_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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 import_agent( self, - ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations.Operation]]: + ) -> Callable[[agent.ImportAgentRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the import agent method over gRPC. Imports the specified agent from a ZIP file. @@ -452,14 +451,14 @@ def import_agent( self._stubs["import_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Agents/ImportAgent", request_serializer=agent.ImportAgentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_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 ZIP file. @@ -493,7 +492,7 @@ def restore_agent( self._stubs["restore_agent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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/dialogflow_v2beta1/services/answer_records/__init__.py b/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py index 7618f55a7..25960120e 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/__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 AnswerRecordsClient from .async_client import AnswerRecordsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py index 5e3908a60..6d2876b4c 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -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 AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport from .client import AnswerRecordsClient @@ -52,31 +49,26 @@ class AnswerRecordsAsyncClient: parse_answer_record_path = staticmethod( AnswerRecordsClient.parse_answer_record_path ) - common_billing_account_path = staticmethod( AnswerRecordsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( AnswerRecordsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(AnswerRecordsClient.common_folder_path) parse_common_folder_path = staticmethod( AnswerRecordsClient.parse_common_folder_path ) - common_organization_path = staticmethod( AnswerRecordsClient.common_organization_path ) parse_common_organization_path = staticmethod( AnswerRecordsClient.parse_common_organization_path ) - common_project_path = staticmethod(AnswerRecordsClient.common_project_path) parse_common_project_path = staticmethod( AnswerRecordsClient.parse_common_project_path ) - common_location_path = staticmethod(AnswerRecordsClient.common_location_path) parse_common_location_path = staticmethod( AnswerRecordsClient.parse_common_location_path @@ -130,7 +122,7 @@ def transport(self) -> AnswerRecordsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, AnswerRecordsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -167,7 +159,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AnswerRecordsClient( credentials=credentials, transport=transport, @@ -190,7 +181,6 @@ async def get_answer_record( request (:class:`google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest`): The request object. Request message for [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -227,16 +217,14 @@ async def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. - request = answer_record.GetAnswerRecordRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -283,7 +271,6 @@ async def list_answer_records( 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. @@ -293,7 +280,7 @@ async def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsAsyncPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -313,7 +300,6 @@ async def list_answer_records( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -348,7 +334,7 @@ async def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = 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]] = (), @@ -371,7 +357,6 @@ async def update_answer_record( 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. @@ -408,12 +393,11 @@ async def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -430,7 +414,6 @@ async def update_answer_record( # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py b/google/cloud/dialogflow_v2beta1/services/answer_records/client.py index a0cceb54b..909a54b14 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/client.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record -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 AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AnswerRecordsGrpcTransport from .transports.grpc_asyncio import AnswerRecordsGrpcAsyncIOTransport @@ -234,7 +231,7 @@ 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, AnswerRecordsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -359,7 +356,6 @@ def get_answer_record( request (google.cloud.dialogflow_v2beta1.types.GetAnswerRecordRequest): The request object. Request message for [AnswerRecords.GetAnswerRecord][google.cloud.dialogflow.v2beta1.AnswerRecords.GetAnswerRecord]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -396,16 +392,14 @@ def get_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a answer_record.GetAnswerRecordRequest. # There's no risk of modifying the input as we've already verified @@ -453,7 +447,6 @@ def list_answer_records( 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. @@ -463,7 +456,7 @@ def list_answer_records( Returns: google.cloud.dialogflow_v2beta1.services.answer_records.pagers.ListAnswerRecordsPager: Response message for - [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. + [AnswerRecords.ListAnswerRecords][google.cloud.dialogflow.v2beta1.AnswerRecords.ListAnswerRecords]. Iterating over this object will yield results and resolve additional pages automatically. @@ -485,10 +478,8 @@ def list_answer_records( # there are no flattened fields. if not isinstance(request, answer_record.ListAnswerRecordsRequest): request = answer_record.ListAnswerRecordsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -519,7 +510,7 @@ def update_answer_record( request: gcd_answer_record.UpdateAnswerRecordRequest = None, *, answer_record: gcd_answer_record.AnswerRecord = 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]] = (), @@ -542,7 +533,6 @@ def update_answer_record( 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. @@ -579,12 +569,11 @@ def update_answer_record( the answers, [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] are returned to the customers. - 2. The customer uses the - [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] - to call the [UpdateAnswerRecord][] method to send - feedback about a specific answer that they believe is - wrong. + [AnswerRecord.name][google.cloud.dialogflow.v2beta1.AnswerRecord.name] + to call the [UpdateAnswerRecord][] method to send + feedback about a specific answer that they believe + is wrong. """ # Create or coerce a protobuf request object. @@ -603,10 +592,8 @@ def update_answer_record( # there are no flattened fields. if not isinstance(request, gcd_answer_record.UpdateAnswerRecordRequest): request = gcd_answer_record.UpdateAnswerRecordRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if answer_record is not None: request.answer_record = answer_record if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py b/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py index 1b0e3ba56..cf85acdeb 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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, diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py index bbb65cf15..e97f4f57d 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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/dialogflow_v2beta1/services/answer_records/transports/base.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py index 1fb664a96..bd8dbeb96 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 AnswerRecordsTransport(abc.ABC): """Abstract transport class for AnswerRecords.""" @@ -47,21 +57,24 @@ class AnswerRecordsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -126,22 +186,20 @@ def _prep_wrapped_messages(self, client_info): @property def get_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.GetAnswerRecordRequest], - typing.Union[ - answer_record.AnswerRecord, typing.Awaitable[answer_record.AnswerRecord] - ], + Union[answer_record.AnswerRecord, Awaitable[answer_record.AnswerRecord]], ]: raise NotImplementedError() @property def list_answer_records( self, - ) -> typing.Callable[ + ) -> Callable[ [answer_record.ListAnswerRecordsRequest], - typing.Union[ + Union[ answer_record.ListAnswerRecordsResponse, - typing.Awaitable[answer_record.ListAnswerRecordsResponse], + Awaitable[answer_record.ListAnswerRecordsResponse], ], ]: raise NotImplementedError() @@ -149,11 +207,10 @@ def list_answer_records( @property def update_answer_record( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_answer_record.UpdateAnswerRecordRequest], - typing.Union[ - gcd_answer_record.AnswerRecord, - typing.Awaitable[gcd_answer_record.AnswerRecord], + Union[ + gcd_answer_record.AnswerRecord, Awaitable[gcd_answer_record.AnswerRecord] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py index 19901a8f3..ec23c6543 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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,21 +13,19 @@ # 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.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) diff --git a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py index a0e18f180..79aab5785 100644 --- a/google/cloud/dialogflow_v2beta1/services/answer_records/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/answer_records/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,22 +13,20 @@ # 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.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record - from .base import AnswerRecordsTransport, DEFAULT_CLIENT_INFO from .grpc import AnswerRecordsGrpcTransport @@ -55,7 +52,7 @@ class AnswerRecordsGrpcAsyncIOTransport(AnswerRecordsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py b/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py index 56b19b0f2..4c5791dcf 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/__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 ContextsClient from .async_client import ContextsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py b/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py index 5aceb21ee..3f2723301 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -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 from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport from .client import ContextsClient @@ -51,25 +48,20 @@ class ContextsAsyncClient: context_path = staticmethod(ContextsClient.context_path) parse_context_path = staticmethod(ContextsClient.parse_context_path) - common_billing_account_path = staticmethod( ContextsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ContextsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ContextsClient.common_folder_path) parse_common_folder_path = staticmethod(ContextsClient.parse_common_folder_path) - common_organization_path = staticmethod(ContextsClient.common_organization_path) parse_common_organization_path = staticmethod( ContextsClient.parse_common_organization_path ) - common_project_path = staticmethod(ContextsClient.common_project_path) parse_common_project_path = staticmethod(ContextsClient.parse_common_project_path) - common_location_path = staticmethod(ContextsClient.common_location_path) parse_common_location_path = staticmethod(ContextsClient.parse_common_location_path) @@ -121,7 +113,7 @@ def transport(self) -> ContextsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ContextsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -158,7 +150,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ContextsClient( credentials=credentials, transport=transport, @@ -199,7 +190,6 @@ async def list_contexts( 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. @@ -229,7 +219,6 @@ async def list_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -290,7 +279,6 @@ async def get_context( 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 +322,6 @@ async def get_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -398,7 +385,6 @@ async def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -442,7 +428,6 @@ async def create_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -473,7 +458,7 @@ async def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = 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]] = (), @@ -496,7 +481,6 @@ async def update_context( 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. @@ -540,7 +524,6 @@ async def update_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -600,7 +583,6 @@ async def delete_context( 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. @@ -621,7 +603,6 @@ async def delete_context( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -676,7 +657,6 @@ async def delete_all_contexts( 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. @@ -697,7 +677,6 @@ async def delete_all_contexts( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/client.py b/google/cloud/dialogflow_v2beta1/services/contexts/client.py index 08291572e..5ff8edf90 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/client.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -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 from .transports.base import ContextsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ContextsGrpcTransport from .transports.grpc_asyncio import ContextsGrpcAsyncIOTransport @@ -236,7 +233,7 @@ 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, ContextsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -379,7 +376,6 @@ def list_contexts( 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. @@ -411,10 +407,8 @@ def list_contexts( # there are no flattened fields. if not isinstance(request, context.ListContextsRequest): request = context.ListContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -471,7 +465,6 @@ def get_context( 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. @@ -517,10 +510,8 @@ def get_context( # there are no flattened fields. if not isinstance(request, context.GetContextRequest): request = context.GetContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -580,7 +571,6 @@ def create_context( This corresponds to the ``context`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -626,10 +616,8 @@ def create_context( # there are no flattened fields. if not isinstance(request, gcd_context.CreateContextRequest): request = gcd_context.CreateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if context is not None: @@ -656,7 +644,7 @@ def update_context( request: gcd_context.UpdateContextRequest = None, *, context: gcd_context.Context = 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]] = (), @@ -679,7 +667,6 @@ def update_context( 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. @@ -725,10 +712,8 @@ def update_context( # there are no flattened fields. if not isinstance(request, gcd_context.UpdateContextRequest): request = gcd_context.UpdateContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if context is not None: request.context = context if update_mask is not None: @@ -784,7 +769,6 @@ def delete_context( 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. @@ -807,10 +791,8 @@ def delete_context( # there are no flattened fields. if not isinstance(request, context.DeleteContextRequest): request = context.DeleteContextRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -861,7 +843,6 @@ def delete_all_contexts( 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. @@ -884,10 +865,8 @@ def delete_all_contexts( # there are no flattened fields. if not isinstance(request, context.DeleteAllContextsRequest): request = context.DeleteAllContextsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py b/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py index 9460cfd11..527c7fd54 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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, diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py index 7437034e4..d25eca3aa 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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/dialogflow_v2beta1/services/contexts/transports/base.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py index 1d3b4783b..90b09437a 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -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 ContextsTransport(abc.ABC): """Abstract transport class for Contexts.""" @@ -48,21 +58,24 @@ class ContextsTransport(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,7 +84,7 @@ 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): @@ -85,29 +98,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -134,56 +194,53 @@ def _prep_wrapped_messages(self, client_info): @property def list_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.ListContextsRequest], - typing.Union[ - context.ListContextsResponse, typing.Awaitable[context.ListContextsResponse] - ], + Union[context.ListContextsResponse, Awaitable[context.ListContextsResponse]], ]: raise NotImplementedError() @property def get_context( self, - ) -> typing.Callable[ - [context.GetContextRequest], - typing.Union[context.Context, typing.Awaitable[context.Context]], + ) -> Callable[ + [context.GetContextRequest], Union[context.Context, Awaitable[context.Context]] ]: raise NotImplementedError() @property def create_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.CreateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def update_context( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_context.UpdateContextRequest], - typing.Union[gcd_context.Context, typing.Awaitable[gcd_context.Context]], + Union[gcd_context.Context, Awaitable[gcd_context.Context]], ]: raise NotImplementedError() @property def delete_context( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteContextRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def delete_all_contexts( self, - ) -> typing.Callable[ + ) -> Callable[ [context.DeleteAllContextsRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py index ae75375c9..393d76c3a 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, 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 @@ -177,7 +175,7 @@ def __init__( 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, @@ -208,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, ) @@ -330,7 +330,9 @@ def update_context( return self._stubs["update_context"] @property - def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty]: + def delete_context( + self, + ) -> Callable[[context.DeleteContextRequest], empty_pb2.Empty]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -349,14 +351,14 @@ def delete_context(self) -> Callable[[context.DeleteContextRequest], empty.Empty self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], empty.Empty]: + ) -> Callable[[context.DeleteAllContextsRequest], empty_pb2.Empty]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -375,7 +377,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py index 3e2d8fdfb..d1a479ef5 100644 --- a/google/cloud/dialogflow_v2beta1/services/contexts/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/contexts/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.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ContextsTransport, DEFAULT_CLIENT_INFO from .grpc import ContextsGrpcTransport @@ -56,7 +53,7 @@ class ContextsGrpcAsyncIOTransport(ContextsTransport): 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, @@ -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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -340,7 +339,7 @@ def update_context( @property def delete_context( self, - ) -> Callable[[context.DeleteContextRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteContextRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete context method over gRPC. Deletes the specified context. @@ -359,14 +358,14 @@ def delete_context( self._stubs["delete_context"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteContext", request_serializer=context.DeleteContextRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_context"] @property def delete_all_contexts( self, - ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty.Empty]]: + ) -> Callable[[context.DeleteAllContextsRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete all contexts method over gRPC. Deletes all active contexts in the specified session. @@ -385,7 +384,7 @@ def delete_all_contexts( self._stubs["delete_all_contexts"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Contexts/DeleteAllContexts", request_serializer=context.DeleteAllContextsRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_all_contexts"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py index 9ab8de0b8..c0cb1cd03 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/__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 ConversationProfilesClient from .async_client import ConversationProfilesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py index a052858ff..4712fa298 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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.dialogflow_v2beta1.services.conversation_profiles import pagers @@ -34,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport from .client import ConversationProfilesClient @@ -54,6 +51,12 @@ class ConversationProfilesAsyncClient: agent_path = staticmethod(ConversationProfilesClient.agent_path) parse_agent_path = staticmethod(ConversationProfilesClient.parse_agent_path) + conversation_model_path = staticmethod( + ConversationProfilesClient.conversation_model_path + ) + parse_conversation_model_path = staticmethod( + ConversationProfilesClient.parse_conversation_model_path + ) conversation_profile_path = staticmethod( ConversationProfilesClient.conversation_profile_path ) @@ -66,31 +69,26 @@ class ConversationProfilesAsyncClient: parse_knowledge_base_path = staticmethod( ConversationProfilesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( ConversationProfilesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationProfilesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationProfilesClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationProfilesClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationProfilesClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationProfilesClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationProfilesClient.common_project_path) parse_common_project_path = staticmethod( ConversationProfilesClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationProfilesClient.common_location_path) parse_common_location_path = staticmethod( ConversationProfilesClient.parse_common_location_path @@ -145,7 +143,7 @@ def transport(self) -> ConversationProfilesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationProfilesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -182,7 +180,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationProfilesClient( credentials=credentials, transport=transport, @@ -214,7 +211,6 @@ async def list_conversation_profiles( 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. @@ -244,7 +240,6 @@ async def list_conversation_profiles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -297,7 +292,6 @@ async def get_conversation_profile( 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. @@ -324,7 +318,6 @@ async def get_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -385,7 +378,6 @@ async def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -412,7 +404,6 @@ async def create_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -443,7 +434,7 @@ async def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = 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 +465,6 @@ async def update_conversation_profile( 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. @@ -501,7 +491,6 @@ async def update_conversation_profile( # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -554,7 +543,6 @@ async def delete_conversation_profile( 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. @@ -575,7 +563,6 @@ async def delete_conversation_profile( # 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/dialogflow_v2beta1/services/conversation_profiles/client.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py index 3e4c17399..40f5c437f 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationProfilesGrpcTransport from .transports.grpc_asyncio import ConversationProfilesGrpcAsyncIOTransport @@ -176,6 +173,24 @@ def parse_agent_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/agent$", path) return m.groupdict() if m else {} + @staticmethod + def conversation_model_path( + project: str, location: str, conversation_model: str, + ) -> str: + """Return a fully-qualified conversation_model string.""" + return "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + + @staticmethod + def parse_conversation_model_path(path: str) -> Dict[str, str]: + """Parse a conversation_model path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/conversationModels/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def conversation_profile_path(project: str, conversation_profile: str,) -> str: """Return a fully-qualified conversation_profile string.""" @@ -285,7 +300,7 @@ 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, ConversationProfilesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -419,7 +434,6 @@ def list_conversation_profiles( 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. @@ -453,10 +467,8 @@ def list_conversation_profiles( request, conversation_profile.ListConversationProfilesRequest ): request = conversation_profile.ListConversationProfilesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -507,7 +519,6 @@ def get_conversation_profile( 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. @@ -536,10 +547,8 @@ def get_conversation_profile( # there are no flattened fields. if not isinstance(request, conversation_profile.GetConversationProfileRequest): request = conversation_profile.GetConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -596,7 +605,6 @@ def create_conversation_profile( This corresponds to the ``conversation_profile`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +635,8 @@ def create_conversation_profile( request, gcd_conversation_profile.CreateConversationProfileRequest ): request = gcd_conversation_profile.CreateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation_profile is not None: @@ -659,7 +665,7 @@ def update_conversation_profile( request: gcd_conversation_profile.UpdateConversationProfileRequest = None, *, conversation_profile: gcd_conversation_profile.ConversationProfile = 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]] = (), @@ -690,7 +696,6 @@ def update_conversation_profile( 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 +726,8 @@ def update_conversation_profile( request, gcd_conversation_profile.UpdateConversationProfileRequest ): request = gcd_conversation_profile.UpdateConversationProfileRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if conversation_profile is not None: request.conversation_profile = conversation_profile if update_mask is not None: @@ -775,7 +778,6 @@ def delete_conversation_profile( 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. @@ -800,10 +802,8 @@ def delete_conversation_profile( request, conversation_profile.DeleteConversationProfileRequest ): request = conversation_profile.DeleteConversationProfileRequest(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/dialogflow_v2beta1/services/conversation_profiles/pagers.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py index 1e03482d0..46566be4f 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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, diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py index e97774bcf..f2a4e2203 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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/dialogflow_v2beta1/services/conversation_profiles/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py index a7f357435..13c13fb36 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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.dialogflow_v2beta1.types import conversation_profile from google.cloud.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -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 ConversationProfilesTransport(abc.ABC): """Abstract transport class for ConversationProfiles.""" @@ -50,21 +60,24 @@ class ConversationProfilesTransport(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,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -143,11 +203,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_conversation_profiles( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.ListConversationProfilesRequest], - typing.Union[ + Union[ conversation_profile.ListConversationProfilesResponse, - typing.Awaitable[conversation_profile.ListConversationProfilesResponse], + Awaitable[conversation_profile.ListConversationProfilesResponse], ], ]: raise NotImplementedError() @@ -155,11 +215,11 @@ def list_conversation_profiles( @property def get_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.GetConversationProfileRequest], - typing.Union[ + Union[ conversation_profile.ConversationProfile, - typing.Awaitable[conversation_profile.ConversationProfile], + Awaitable[conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -167,11 +227,11 @@ def get_conversation_profile( @property def create_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.CreateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def create_conversation_profile( @property def update_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation_profile.UpdateConversationProfileRequest], - typing.Union[ + Union[ gcd_conversation_profile.ConversationProfile, - typing.Awaitable[gcd_conversation_profile.ConversationProfile], + Awaitable[gcd_conversation_profile.ConversationProfile], ], ]: raise NotImplementedError() @@ -191,9 +251,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation_profile.DeleteConversationProfileRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py index 80cd9e78f..4641c6bfb 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, 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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -358,7 +358,9 @@ def update_conversation_profile( @property def delete_conversation_profile( self, - ) -> Callable[[conversation_profile.DeleteConversationProfileRequest], empty.Empty]: + ) -> Callable[ + [conversation_profile.DeleteConversationProfileRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete conversation profile method over gRPC. Deletes the specified conversation profile. @@ -377,7 +379,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py index 72244a461..4bb6d208b 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversation_profiles/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversation_profiles/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.dialogflow_v2beta1.types import ( conversation_profile as gcd_conversation_profile, ) -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import ConversationProfilesTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationProfilesGrpcTransport @@ -58,7 +55,7 @@ class ConversationProfilesGrpcAsyncIOTransport(ConversationProfilesTransport): 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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -363,7 +362,8 @@ def update_conversation_profile( def delete_conversation_profile( self, ) -> Callable[ - [conversation_profile.DeleteConversationProfileRequest], Awaitable[empty.Empty] + [conversation_profile.DeleteConversationProfileRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the delete conversation profile method over gRPC. @@ -383,7 +383,7 @@ def delete_conversation_profile( self._stubs["delete_conversation_profile"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.ConversationProfiles/DeleteConversationProfile", request_serializer=conversation_profile.DeleteConversationProfileRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_conversation_profile"] diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py index cce809abe..f6f6b90ff 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/__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 ConversationsClient from .async_client import ConversationsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py b/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py index cf4fb1475..705f69156 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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.dialogflow_v2beta1.services.conversations import pagers from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport from .client import ConversationsClient @@ -59,31 +56,26 @@ class ConversationsAsyncClient: ) message_path = staticmethod(ConversationsClient.message_path) parse_message_path = staticmethod(ConversationsClient.parse_message_path) - common_billing_account_path = staticmethod( ConversationsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ConversationsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ConversationsClient.common_folder_path) parse_common_folder_path = staticmethod( ConversationsClient.parse_common_folder_path ) - common_organization_path = staticmethod( ConversationsClient.common_organization_path ) parse_common_organization_path = staticmethod( ConversationsClient.parse_common_organization_path ) - common_project_path = staticmethod(ConversationsClient.common_project_path) parse_common_project_path = staticmethod( ConversationsClient.parse_common_project_path ) - common_location_path = staticmethod(ConversationsClient.common_location_path) parse_common_location_path = staticmethod( ConversationsClient.parse_common_location_path @@ -137,7 +129,7 @@ def transport(self) -> ConversationsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ConversationsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -174,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ConversationsClient( credentials=credentials, transport=transport, @@ -231,7 +222,6 @@ async def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -263,7 +253,6 @@ async def create_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -313,7 +302,6 @@ async def list_conversations( 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. @@ -323,7 +311,7 @@ async def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsAsyncPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -343,7 +331,6 @@ async def list_conversations( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -395,7 +382,6 @@ async def get_conversation( 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. @@ -427,7 +413,6 @@ async def get_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -476,7 +461,6 @@ async def complete_conversation( 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. @@ -508,7 +492,6 @@ async def complete_conversation( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -557,7 +540,6 @@ async def batch_create_messages( 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. @@ -584,7 +566,6 @@ async def batch_create_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -635,7 +616,6 @@ async def list_messages( 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. @@ -645,7 +625,7 @@ async def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesAsyncPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. @@ -665,7 +645,6 @@ async def list_messages( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/client.py b/google/cloud/dialogflow_v2beta1/services/conversations/client.py index 5dee0325f..0ca2843b7 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/client.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - +from google.protobuf import timestamp_pb2 # type: ignore from .transports.base import ConversationsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ConversationsGrpcTransport from .transports.grpc_asyncio import ConversationsGrpcAsyncIOTransport @@ -267,7 +264,7 @@ 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, ConversationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -426,7 +423,6 @@ def create_conversation( This corresponds to the ``conversation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -460,10 +456,8 @@ def create_conversation( # there are no flattened fields. if not isinstance(request, gcd_conversation.CreateConversationRequest): request = gcd_conversation.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if conversation is not None: @@ -509,7 +503,6 @@ def list_conversations( 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. @@ -519,7 +512,7 @@ def list_conversations( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListConversationsPager: The response message for - [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. + [Conversations.ListConversations][google.cloud.dialogflow.v2beta1.Conversations.ListConversations]. Iterating over this object will yield results and resolve additional pages automatically. @@ -541,10 +534,8 @@ def list_conversations( # there are no flattened fields. if not isinstance(request, conversation.ListConversationsRequest): request = conversation.ListConversationsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -592,7 +583,6 @@ def get_conversation( 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. @@ -626,10 +616,8 @@ def get_conversation( # there are no flattened fields. if not isinstance(request, conversation.GetConversationRequest): request = conversation.GetConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -674,7 +662,6 @@ def complete_conversation( 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. @@ -708,10 +695,8 @@ def complete_conversation( # there are no flattened fields. if not isinstance(request, conversation.CompleteConversationRequest): request = conversation.CompleteConversationRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -756,7 +741,6 @@ def batch_create_messages( 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. @@ -785,10 +769,8 @@ def batch_create_messages( # there are no flattened fields. if not isinstance(request, conversation.BatchCreateMessagesRequest): request = conversation.BatchCreateMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -835,7 +817,6 @@ def list_messages( 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. @@ -845,7 +826,7 @@ def list_messages( Returns: google.cloud.dialogflow_v2beta1.services.conversations.pagers.ListMessagesPager: The response message for - [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. + [Conversations.ListMessages][google.cloud.dialogflow.v2beta1.Conversations.ListMessages]. Iterating over this object will yield results and resolve additional pages automatically. @@ -867,10 +848,8 @@ def list_messages( # there are no flattened fields. if not isinstance(request, conversation.ListMessagesRequest): request = conversation.ListMessagesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py b/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py index f9a2ca203..3cb4d683a 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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, diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py index 6597b6d01..2989914f7 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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/dialogflow_v2beta1/services/conversations/transports/base.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py index ecc38991b..47f6e70ae 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 ConversationsTransport(abc.ABC): """Abstract transport class for Conversations.""" @@ -47,21 +57,24 @@ class ConversationsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -137,23 +197,20 @@ def _prep_wrapped_messages(self, client_info): @property def create_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_conversation.CreateConversationRequest], - typing.Union[ - gcd_conversation.Conversation, - typing.Awaitable[gcd_conversation.Conversation], - ], + Union[gcd_conversation.Conversation, Awaitable[gcd_conversation.Conversation]], ]: raise NotImplementedError() @property def list_conversations( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListConversationsRequest], - typing.Union[ + Union[ conversation.ListConversationsResponse, - typing.Awaitable[conversation.ListConversationsResponse], + Awaitable[conversation.ListConversationsResponse], ], ]: raise NotImplementedError() @@ -161,33 +218,29 @@ def list_conversations( @property def get_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.GetConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def complete_conversation( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.CompleteConversationRequest], - typing.Union[ - conversation.Conversation, typing.Awaitable[conversation.Conversation] - ], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], ]: raise NotImplementedError() @property def batch_create_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.BatchCreateMessagesRequest], - typing.Union[ + Union[ conversation.BatchCreateMessagesResponse, - typing.Awaitable[conversation.BatchCreateMessagesResponse], + Awaitable[conversation.BatchCreateMessagesResponse], ], ]: raise NotImplementedError() @@ -195,11 +248,11 @@ def batch_create_messages( @property def list_messages( self, - ) -> typing.Callable[ + ) -> Callable[ [conversation.ListMessagesRequest], - typing.Union[ + Union[ conversation.ListMessagesResponse, - typing.Awaitable[conversation.ListMessagesResponse], + Awaitable[conversation.ListMessagesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py index c0f5c981a..c61488ce1 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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,21 +13,19 @@ # 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.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - from .base import ConversationsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) diff --git a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py index a00f0288d..9502a95c4 100644 --- a/google/cloud/dialogflow_v2beta1/services/conversations/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/conversations/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,22 +13,20 @@ # 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.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation - from .base import ConversationsTransport, DEFAULT_CLIENT_INFO from .grpc import ConversationsGrpcTransport @@ -55,7 +52,7 @@ class ConversationsGrpcAsyncIOTransport(ConversationsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2beta1/services/documents/__init__.py b/google/cloud/dialogflow_v2beta1/services/documents/__init__.py index 5f6db6815..f610c36b0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/__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 DocumentsClient from .async_client import DocumentsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/documents/async_client.py b/google/cloud/dialogflow_v2beta1/services/documents/async_client.py index 391764994..346fa54ba 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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,9 +32,8 @@ from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs -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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport from .client import DocumentsClient @@ -54,25 +51,20 @@ class DocumentsAsyncClient: document_path = staticmethod(DocumentsClient.document_path) parse_document_path = staticmethod(DocumentsClient.parse_document_path) - common_billing_account_path = staticmethod( DocumentsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( DocumentsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(DocumentsClient.common_folder_path) parse_common_folder_path = staticmethod(DocumentsClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentsClient.common_organization_path) parse_common_organization_path = staticmethod( DocumentsClient.parse_common_organization_path ) - common_project_path = staticmethod(DocumentsClient.common_project_path) parse_common_project_path = staticmethod(DocumentsClient.parse_common_project_path) - common_location_path = staticmethod(DocumentsClient.common_location_path) parse_common_location_path = staticmethod( DocumentsClient.parse_common_location_path @@ -126,7 +118,7 @@ def transport(self) -> DocumentsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, DocumentsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -163,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = DocumentsClient( credentials=credentials, transport=transport, @@ -197,7 +188,6 @@ async def list_documents( 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. @@ -227,7 +217,6 @@ async def list_documents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -282,7 +271,6 @@ async def get_document( 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. @@ -316,7 +304,6 @@ async def get_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -372,7 +359,6 @@ async def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not 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,7 +396,6 @@ async def create_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -453,13 +438,14 @@ async def import_documents( metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Args: request (:class:`google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest`): The request object. Request message for [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -477,7 +463,6 @@ async def import_documents( """ # Create or coerce a protobuf request object. - request = document.ImportDocumentsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -533,7 +518,6 @@ async def delete_document( 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. @@ -573,7 +557,6 @@ async def delete_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -598,7 +581,7 @@ async def delete_document( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -610,7 +593,7 @@ async def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = 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]] = (), @@ -637,7 +620,6 @@ async def update_document( 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. @@ -675,7 +657,6 @@ async def update_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -754,7 +735,6 @@ async def reload_document( This corresponds to the ``gcs_source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -792,7 +772,6 @@ async def reload_document( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if gcs_source is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/documents/client.py b/google/cloud/dialogflow_v2beta1/services/documents/client.py index a7890ee89..f734b04c8 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/client.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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,9 +36,8 @@ from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs -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 empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore from .transports.base import DocumentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import DocumentsGrpcTransport from .transports.grpc_asyncio import DocumentsGrpcAsyncIOTransport @@ -239,7 +236,7 @@ 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, DocumentsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -375,7 +372,6 @@ def list_documents( 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. @@ -407,10 +403,8 @@ def list_documents( # there are no flattened fields. if not isinstance(request, document.ListDocumentsRequest): request = document.ListDocumentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -461,7 +455,6 @@ def get_document( 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. @@ -497,10 +490,8 @@ def get_document( # there are no flattened fields. if not isinstance(request, document.GetDocumentRequest): request = document.GetDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -552,7 +543,6 @@ def create_document( This corresponds to the ``document`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -592,10 +582,8 @@ def create_document( # there are no flattened fields. if not isinstance(request, gcd_document.CreateDocumentRequest): request = gcd_document.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if document is not None: @@ -634,13 +622,14 @@ def import_documents( metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Args: request (google.cloud.dialogflow_v2beta1.types.ImportDocumentsRequest): The request object. Request message for [Documents.ImportDocuments][google.cloud.dialogflow.v2beta1.Documents.ImportDocuments]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -658,7 +647,6 @@ def import_documents( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a document.ImportDocumentsRequest. # There's no risk of modifying the input as we've already verified @@ -715,7 +703,6 @@ def delete_document( 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. @@ -757,10 +744,8 @@ def delete_document( # there are no flattened fields. if not isinstance(request, document.DeleteDocumentRequest): request = document.DeleteDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -781,7 +766,7 @@ def delete_document( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=document.KnowledgeOperationMetadata, ) @@ -793,7 +778,7 @@ def update_document( request: gcd_document.UpdateDocumentRequest = None, *, document: gcd_document.Document = 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]] = (), @@ -820,7 +805,6 @@ def update_document( 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. @@ -860,10 +844,8 @@ def update_document( # there are no flattened fields. if not isinstance(request, gcd_document.UpdateDocumentRequest): request = gcd_document.UpdateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if document is not None: request.document = document if update_mask is not None: @@ -938,7 +920,6 @@ def reload_document( This corresponds to the ``gcs_source`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -978,10 +959,8 @@ def reload_document( # there are no flattened fields. if not isinstance(request, document.ReloadDocumentRequest): request = document.ReloadDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if gcs_source is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/documents/pagers.py b/google/cloud/dialogflow_v2beta1/services/documents/pagers.py index 9169210c7..cac79babd 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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, diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py index af02ba19c..5d4948aa0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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/dialogflow_v2beta1/services/documents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py index 352d60dce..992198722 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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,22 +13,22 @@ # 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.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -40,6 +39,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 DocumentsTransport(abc.ABC): """Abstract transport class for Documents.""" @@ -49,21 +59,24 @@ class DocumentsTransport(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 @@ -72,7 +85,7 @@ 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): @@ -86,29 +99,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -143,11 +203,10 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def list_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ListDocumentsRequest], - typing.Union[ - document.ListDocumentsResponse, - typing.Awaitable[document.ListDocumentsResponse], + Union[ + document.ListDocumentsResponse, Awaitable[document.ListDocumentsResponse] ], ]: raise NotImplementedError() @@ -155,54 +214,54 @@ def list_documents( @property def get_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.GetDocumentRequest], - typing.Union[document.Document, typing.Awaitable[document.Document]], + Union[document.Document, Awaitable[document.Document]], ]: raise NotImplementedError() @property def create_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.CreateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def import_documents( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ImportDocumentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def delete_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.DeleteDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def update_document( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_document.UpdateDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def reload_document( self, - ) -> typing.Callable[ + ) -> Callable[ [document.ReloadDocumentRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py index 11c7488ee..822acc7f0 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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,23 +13,21 @@ # 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.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, 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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -301,7 +301,7 @@ def get_document( @property def create_document( self, - ) -> Callable[[gcd_document.CreateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.CreateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the create document method over gRPC. Creates a new document. @@ -323,18 +323,20 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def import_documents( self, - ) -> Callable[[document.ImportDocumentsRequest], operations.Operation]: + ) -> Callable[[document.ImportDocumentsRequest], operations_pb2.Operation]: r"""Return a callable for the import documents method over gRPC. Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Returns: Callable[[~.ImportDocumentsRequest], @@ -350,14 +352,14 @@ def import_documents( self._stubs["import_documents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments", request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_documents"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], operations.Operation]: + ) -> Callable[[document.DeleteDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -379,14 +381,14 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @property def update_document( self, - ) -> Callable[[gcd_document.UpdateDocumentRequest], operations.Operation]: + ) -> Callable[[gcd_document.UpdateDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the update document method over gRPC. Updates the specified document. @@ -408,14 +410,14 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], operations.Operation]: + ) -> Callable[[document.ReloadDocumentRequest], operations_pb2.Operation]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -445,7 +447,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py index 112d72a50..56968f9fc 100644 --- a/google/cloud/dialogflow_v2beta1/services/documents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/documents/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,24 +13,22 @@ # 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.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import DocumentsTransport, DEFAULT_CLIENT_INFO from .grpc import DocumentsGrpcTransport @@ -57,7 +54,7 @@ class DocumentsGrpcAsyncIOTransport(DocumentsTransport): 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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -310,7 +309,7 @@ def get_document( def create_document( self, ) -> Callable[ - [gcd_document.CreateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.CreateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the create document method over gRPC. @@ -333,18 +332,22 @@ def create_document( self._stubs["create_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/CreateDocument", request_serializer=gcd_document.CreateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["create_document"] @property def import_documents( self, - ) -> Callable[[document.ImportDocumentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ImportDocumentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the import documents method over gRPC. Create documents by importing data from external - sources. + sources. Dialogflow supports up to 350 documents in each + request. If you try to import more, Dialogflow will + return an error. Returns: Callable[[~.ImportDocumentsRequest], @@ -360,14 +363,16 @@ def import_documents( self._stubs["import_documents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ImportDocuments", request_serializer=document.ImportDocumentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_documents"] @property def delete_document( self, - ) -> Callable[[document.DeleteDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.DeleteDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete document method over gRPC. Deletes the specified document. @@ -389,7 +394,7 @@ def delete_document( self._stubs["delete_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument", request_serializer=document.DeleteDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["delete_document"] @@ -397,7 +402,7 @@ def delete_document( def update_document( self, ) -> Callable[ - [gcd_document.UpdateDocumentRequest], Awaitable[operations.Operation] + [gcd_document.UpdateDocumentRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the update document method over gRPC. @@ -420,14 +425,16 @@ def update_document( self._stubs["update_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/UpdateDocument", request_serializer=gcd_document.UpdateDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["update_document"] @property def reload_document( self, - ) -> Callable[[document.ReloadDocumentRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [document.ReloadDocumentRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the reload document method over gRPC. Reloads the specified document from its specified source, @@ -457,7 +464,7 @@ def reload_document( self._stubs["reload_document"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Documents/ReloadDocument", request_serializer=document.ReloadDocumentRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["reload_document"] diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py b/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py index f52849c66..77cd53e9c 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/entity_types/async_client.py b/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py index 8c323260b..bcf51a49c 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -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 EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport from .client import EntityTypesClient @@ -54,27 +51,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 @@ -128,7 +120,7 @@ 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, @@ -165,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EntityTypesClient( credentials=credentials, transport=transport, @@ -210,7 +201,6 @@ async def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -240,7 +230,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 if language_code is not None: @@ -308,7 +297,6 @@ async def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -348,7 +336,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 if language_code is not None: @@ -416,7 +403,6 @@ async def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -456,7 +442,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: @@ -490,7 +475,7 @@ async def update_entity_type( *, entity_type: gcd_entity_type.EntityType = None, language_code: str = 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]] = (), @@ -523,7 +508,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. @@ -563,7 +547,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 language_code is not None: @@ -618,7 +601,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. @@ -639,7 +621,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 @@ -678,7 +659,6 @@ async def batch_update_entity_types( request (:class:`google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest`): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -696,7 +676,6 @@ async def batch_update_entity_types( """ # Create or coerce a protobuf request object. - request = entity_type.BatchUpdateEntityTypesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -721,7 +700,7 @@ async def batch_update_entity_types( response, self._client._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -761,7 +740,6 @@ async def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -801,10 +779,8 @@ async def batch_delete_entity_types( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if entity_type_names: request.entity_type_names.extend(entity_type_names) @@ -829,8 +805,8 @@ async def batch_delete_entity_types( 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. @@ -881,7 +857,6 @@ async def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -921,12 +896,10 @@ async def batch_create_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -951,8 +924,8 @@ async def batch_create_entities( 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. @@ -1007,7 +980,6 @@ async def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1047,12 +1019,10 @@ async def batch_update_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entities: request.entities.extend(entities) @@ -1077,8 +1047,8 @@ async def batch_update_entities( 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. @@ -1132,7 +1102,6 @@ async def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1172,12 +1141,10 @@ async def batch_delete_entities( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if language_code is not None: request.language_code = language_code - if entity_values: request.entity_values.extend(entity_values) @@ -1202,8 +1169,8 @@ async def batch_delete_entities( 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/dialogflow_v2beta1/services/entity_types/client.py b/google/cloud/dialogflow_v2beta1/services/entity_types/client.py index 32b206474..610f57cc0 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/client.py +++ b/google/cloud/dialogflow_v2beta1/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 @@ -37,10 +35,9 @@ from google.cloud.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -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 EntityTypesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import EntityTypesGrpcTransport from .transports.grpc_asyncio import EntityTypesGrpcAsyncIOTransport @@ -238,7 +235,7 @@ 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, @@ -385,7 +382,6 @@ def list_entity_types( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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,10 +413,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 if language_code is not None: @@ -484,7 +478,6 @@ def get_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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,10 +519,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 if language_code is not None: @@ -593,7 +584,6 @@ def create_entity_type( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -635,10 +625,8 @@ def create_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.CreateEntityTypeRequest): request = gcd_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: @@ -668,7 +656,7 @@ def update_entity_type( *, entity_type: gcd_entity_type.EntityType = None, language_code: str = 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]] = (), @@ -701,7 +689,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. @@ -743,10 +730,8 @@ def update_entity_type( # there are no flattened fields. if not isinstance(request, gcd_entity_type.UpdateEntityTypeRequest): request = gcd_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 language_code is not None: @@ -797,7 +782,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. @@ -820,10 +804,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 @@ -858,7 +840,6 @@ def batch_update_entity_types( request (google.cloud.dialogflow_v2beta1.types.BatchUpdateEntityTypesRequest): The request object. The request message for [EntityTypes.BatchUpdateEntityTypes][google.cloud.dialogflow.v2beta1.EntityTypes.BatchUpdateEntityTypes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -876,7 +857,6 @@ def batch_update_entity_types( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a entity_type.BatchUpdateEntityTypesRequest. # There's no risk of modifying the input as we've already verified @@ -904,7 +884,7 @@ def batch_update_entity_types( response, self._transport.operations_client, entity_type.BatchUpdateEntityTypesResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -944,7 +924,6 @@ def batch_delete_entity_types( This corresponds to the ``entity_type_names`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -986,10 +965,8 @@ def batch_delete_entity_types( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntityTypesRequest): request = entity_type.BatchDeleteEntityTypesRequest(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_names is not None: @@ -1014,8 +991,8 @@ def batch_delete_entity_types( 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. @@ -1066,7 +1043,6 @@ def batch_create_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1108,10 +1084,8 @@ def batch_create_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchCreateEntitiesRequest): request = entity_type.BatchCreateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1136,8 +1110,8 @@ def batch_create_entities( 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. @@ -1192,7 +1166,6 @@ def batch_update_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1234,10 +1207,8 @@ def batch_update_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchUpdateEntitiesRequest): request = entity_type.BatchUpdateEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entities is not None: @@ -1262,8 +1233,8 @@ def batch_update_entities( 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. @@ -1317,7 +1288,6 @@ def batch_delete_entities( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1359,10 +1329,8 @@ def batch_delete_entities( # there are no flattened fields. if not isinstance(request, entity_type.BatchDeleteEntitiesRequest): request = entity_type.BatchDeleteEntitiesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if entity_values is not None: @@ -1387,8 +1355,8 @@ def batch_delete_entities( 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/dialogflow_v2beta1/services/entity_types/pagers.py b/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py index 06d3999b4..66667e1c8 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/pagers.py +++ b/google/cloud/dialogflow_v2beta1/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, diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py index 963959d1a..07ea82e1b 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py index 3b3c283cd..90ab77975 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -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 EntityTypesTransport(abc.ABC): """Abstract transport class for EntityTypes.""" @@ -50,21 +60,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 @@ -73,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -163,11 +223,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @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() @@ -175,85 +235,81 @@ 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[ [gcd_entity_type.CreateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_entity_type.EntityType]], ]: raise NotImplementedError() @property def update_entity_type( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_entity_type.UpdateEntityTypeRequest], - typing.Union[ - gcd_entity_type.EntityType, typing.Awaitable[gcd_entity_type.EntityType] - ], + Union[gcd_entity_type.EntityType, Awaitable[gcd_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() @property def batch_update_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entity_types( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntityTypesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_create_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchCreateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_update_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchUpdateEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_entities( self, - ) -> typing.Callable[ + ) -> Callable[ [entity_type.BatchDeleteEntitiesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py index 3cd835d14..f85284d34 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -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 EntityTypesTransport, 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 @@ -180,7 +178,7 @@ def __init__( 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,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, ) @@ -355,7 +355,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. @@ -374,14 +374,16 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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"] @property def batch_update_entity_types( self, - ) -> Callable[[entity_type.BatchUpdateEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchUpdateEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch update entity types method over gRPC. Updates/Creates multiple entity types in the specified agent. @@ -402,14 +404,16 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @property def batch_delete_entity_types( self, - ) -> Callable[[entity_type.BatchDeleteEntityTypesRequest], operations.Operation]: + ) -> Callable[ + [entity_type.BatchDeleteEntityTypesRequest], operations_pb2.Operation + ]: r"""Return a callable for the batch delete entity types method over gRPC. Deletes entity types in the specified agent. Operation @@ -429,14 +433,14 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @property def batch_create_entities( self, - ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchCreateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch create entities method over gRPC. Creates multiple new entities in the specified entity type. @@ -458,14 +462,14 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @property def batch_update_entities( self, - ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchUpdateEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch update entities method over gRPC. Updates or creates multiple entities in the specified entity @@ -489,14 +493,14 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @property def batch_delete_entities( self, - ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations.Operation]: + ) -> Callable[[entity_type.BatchDeleteEntitiesRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete entities method over gRPC. Deletes entities in the specified entity type. @@ -518,7 +522,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py index c4f4439fd..7c698f704 100644 --- a/google/cloud/dialogflow_v2beta1/services/entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type -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 EntityTypesTransport, DEFAULT_CLIENT_INFO from .grpc import EntityTypesGrpcTransport @@ -58,7 +55,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, @@ -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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -364,7 +363,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. @@ -383,7 +382,7 @@ def delete_entity_type( self._stubs["delete_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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"] @@ -391,7 +390,7 @@ def delete_entity_type( def batch_update_entity_types( self, ) -> Callable[ - [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entity types method over gRPC. @@ -413,7 +412,7 @@ def batch_update_entity_types( self._stubs["batch_update_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntityTypes", request_serializer=entity_type.BatchUpdateEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entity_types"] @@ -421,7 +420,7 @@ def batch_update_entity_types( def batch_delete_entity_types( self, ) -> Callable[ - [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntityTypesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entity types method over gRPC. @@ -442,7 +441,7 @@ def batch_delete_entity_types( self._stubs["batch_delete_entity_types"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntityTypes", request_serializer=entity_type.BatchDeleteEntityTypesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entity_types"] @@ -450,7 +449,7 @@ def batch_delete_entity_types( def batch_create_entities( self, ) -> Callable[ - [entity_type.BatchCreateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchCreateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch create entities method over gRPC. @@ -473,7 +472,7 @@ def batch_create_entities( self._stubs["batch_create_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchCreateEntities", request_serializer=entity_type.BatchCreateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_create_entities"] @@ -481,7 +480,7 @@ def batch_create_entities( def batch_update_entities( self, ) -> Callable[ - [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchUpdateEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch update entities method over gRPC. @@ -506,7 +505,7 @@ def batch_update_entities( self._stubs["batch_update_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchUpdateEntities", request_serializer=entity_type.BatchUpdateEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_entities"] @@ -514,7 +513,7 @@ def batch_update_entities( def batch_delete_entities( self, ) -> Callable[ - [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations.Operation] + [entity_type.BatchDeleteEntitiesRequest], Awaitable[operations_pb2.Operation] ]: r"""Return a callable for the batch delete entities method over gRPC. @@ -537,7 +536,7 @@ def batch_delete_entities( self._stubs["batch_delete_entities"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.EntityTypes/BatchDeleteEntities", request_serializer=entity_type.BatchDeleteEntitiesRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_entities"] diff --git a/google/cloud/dialogflow_v2beta1/services/environments/__init__.py b/google/cloud/dialogflow_v2beta1/services/environments/__init__.py index a67f2316d..0c2be9484 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/environments/async_client.py b/google/cloud/dialogflow_v2beta1/services/environments/async_client.py index 232e39ebf..28eee02f8 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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,15 +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.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.types import environment - +from google.cloud.dialogflow_v2beta1.types import fulfillment +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 @@ -48,27 +47,24 @@ class EnvironmentsAsyncClient: environment_path = staticmethod(EnvironmentsClient.environment_path) parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_path) - + fulfillment_path = staticmethod(EnvironmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(EnvironmentsClient.parse_fulfillment_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 @@ -122,7 +118,7 @@ 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, @@ -159,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = EnvironmentsClient( credentials=credentials, transport=transport, @@ -193,7 +188,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. @@ -223,7 +217,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 @@ -253,6 +246,324 @@ async def list_environments( # Done; return the response. return response + async def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest`): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentRequest(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.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest`): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.CreateEnvironmentRequest(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.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest`): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + request = environment.UpdateEnvironmentRequest(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.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest`): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + request = environment.DeleteEnvironmentRequest(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.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryAsyncPager: + r"""Gets the history of the specified environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest`): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + 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.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryAsyncPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = environment.GetEnvironmentHistoryRequest(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.get_environment_history, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GetEnvironmentHistoryAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2beta1/services/environments/client.py b/google/cloud/dialogflow_v2beta1/services/environments/client.py index a9e38d254..4e9d241ba 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/client.py +++ b/google/cloud/dialogflow_v2beta1/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 @@ -34,7 +32,8 @@ from google.cloud.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.types import environment - +from google.cloud.dialogflow_v2beta1.types import fulfillment +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 @@ -170,6 +169,17 @@ def parse_environment_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def fulfillment_path(project: str,) -> str: + """Return a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project,) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str, str]: + """Parse a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Return a fully-qualified billing_account string.""" @@ -232,7 +242,7 @@ 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, @@ -368,7 +378,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. @@ -400,10 +409,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 @@ -429,6 +436,329 @@ def list_environments( # Done; return the response. return response + def get_environment( + self, + request: environment.GetEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Retrieves the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentRequest): + The request object. The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentRequest): + request = environment.GetEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_environment( + self, + request: environment.CreateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Creates an agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateEnvironmentRequest): + The request object. The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.CreateEnvironmentRequest): + request = environment.CreateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_environment( + self, + request: environment.UpdateEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> environment.Environment: + r"""Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateEnvironmentRequest): + The request object. The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + 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.dialogflow_v2beta1.types.Environment: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.UpdateEnvironmentRequest): + request = environment.UpdateEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("environment.name", request.environment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_environment( + self, + request: environment.DeleteEnvironmentRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes the specified agent environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteEnvironmentRequest): + The request object. The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.DeleteEnvironmentRequest): + request = environment.DeleteEnvironmentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_environment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_environment_history( + self, + request: environment.GetEnvironmentHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GetEnvironmentHistoryPager: + r"""Gets the history of the specified environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The request object. The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + 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.dialogflow_v2beta1.services.environments.pagers.GetEnvironmentHistoryPager: + The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a environment.GetEnvironmentHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, environment.GetEnvironmentHistoryRequest): + request = environment.GetEnvironmentHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_environment_history] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GetEnvironmentHistoryPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( diff --git a/google/cloud/dialogflow_v2beta1/services/environments/pagers.py b/google/cloud/dialogflow_v2beta1/services/environments/pagers.py index c46469235..b69943383 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/pagers.py +++ b/google/cloud/dialogflow_v2beta1/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, @@ -155,3 +153,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__iter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., environment.EnvironmentHistory], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[environment.EnvironmentHistory.Entry]: + for page in self.pages: + yield from page.entries + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GetEnvironmentHistoryAsyncPager: + """A pager for iterating through ``get_environment_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` object, and + provides an ``__aiter__`` method to iterate through its + ``entries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GetEnvironmentHistory`` requests and continue to iterate + through the ``entries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.EnvironmentHistory` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[environment.EnvironmentHistory]], + request: environment.GetEnvironmentHistoryRequest, + response: environment.EnvironmentHistory, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.GetEnvironmentHistoryRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.EnvironmentHistory): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = environment.GetEnvironmentHistoryRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[environment.EnvironmentHistory]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[environment.EnvironmentHistory.Entry]: + async def async_generator(): + async for page in self.pages: + for response in page.entries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py index aff44bcdd..c72efee48 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/environments/transports/base.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py index d48fa645e..16fe7c632 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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,19 +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.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +37,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.""" @@ -46,21 +57,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 @@ -69,7 +83,7 @@ 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): @@ -83,45 +97,156 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { self.list_environments: gapic_v1.method.wrap_method( self.list_environments, default_timeout=None, client_info=client_info, ), + self.get_environment: gapic_v1.method.wrap_method( + self.get_environment, default_timeout=None, client_info=client_info, + ), + self.create_environment: gapic_v1.method.wrap_method( + self.create_environment, default_timeout=None, client_info=client_info, + ), + self.update_environment: gapic_v1.method.wrap_method( + self.update_environment, default_timeout=None, client_info=client_info, + ), + self.delete_environment: gapic_v1.method.wrap_method( + self.delete_environment, default_timeout=None, client_info=client_info, + ), + self.get_environment_history: gapic_v1.method.wrap_method( + self.get_environment_history, + default_timeout=None, + client_info=client_info, + ), } @property def list_environments( self, - ) -> typing.Callable[ + ) -> Callable[ [environment.ListEnvironmentsRequest], - typing.Union[ + Union[ environment.ListEnvironmentsResponse, - typing.Awaitable[environment.ListEnvironmentsResponse], + Awaitable[environment.ListEnvironmentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], + Union[environment.Environment, Awaitable[environment.Environment]], + ]: + raise NotImplementedError() + + @property + def delete_environment( + self, + ) -> Callable[ + [environment.DeleteEnvironmentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Union[ + environment.EnvironmentHistory, Awaitable[environment.EnvironmentHistory] ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py index 6fb0cd7e2..f2bfbb0a0 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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,20 +13,19 @@ # 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.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO @@ -51,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, @@ -65,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 @@ -175,7 +174,7 @@ def __init__( 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, @@ -206,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, ) @@ -251,5 +252,149 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[[environment.GetEnvironmentRequest], environment.Environment]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + ~.Environment]: + 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_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[[environment.CreateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[[environment.UpdateEnvironmentRequest], environment.Environment]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + ~.Environment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], environment.EnvironmentHistory + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + ~.EnvironmentHistory]: + 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_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py index 52b0b3ba7..af0d1bcc8 100644 --- a/google/cloud/dialogflow_v2beta1/services/environments/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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,21 +13,20 @@ # 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.dialogflow_v2beta1.types import environment - +from google.protobuf import empty_pb2 # type: ignore from .base import EnvironmentsTransport, DEFAULT_CLIENT_INFO from .grpc import EnvironmentsGrpcTransport @@ -54,7 +52,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, @@ -81,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, ) @@ -95,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, @@ -109,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 @@ -167,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -256,5 +256,156 @@ def list_environments( ) return self._stubs["list_environments"] + @property + def get_environment( + self, + ) -> Callable[ + [environment.GetEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the get environment method over gRPC. + + Retrieves the specified agent environment. + + Returns: + Callable[[~.GetEnvironmentRequest], + Awaitable[~.Environment]]: + 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_environment" not in self._stubs: + self._stubs["get_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironment", + request_serializer=environment.GetEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["get_environment"] + + @property + def create_environment( + self, + ) -> Callable[ + [environment.CreateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the create environment method over gRPC. + + Creates an agent environment. + + Returns: + Callable[[~.CreateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_environment" not in self._stubs: + self._stubs["create_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/CreateEnvironment", + request_serializer=environment.CreateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["create_environment"] + + @property + def update_environment( + self, + ) -> Callable[ + [environment.UpdateEnvironmentRequest], Awaitable[environment.Environment] + ]: + r"""Return a callable for the update environment method over gRPC. + + Updates the specified agent environment. + + This method allows you to deploy new agent versions into the + environment. When an environment is pointed to a new agent + version by setting ``environment.agent_version``, the + environment is temporarily set to the ``LOADING`` state. During + that time, the environment keeps on serving the previous version + of the agent. After the new agent version is done loading, the + environment is set back to the ``RUNNING`` state. You can use + "-" as Environment ID in environment name to update version in + "draft" environment. WARNING: this will negate all recent + changes to draft and can't be undone. You may want to save the + draft to a version before calling this function. + + Returns: + Callable[[~.UpdateEnvironmentRequest], + Awaitable[~.Environment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_environment" not in self._stubs: + self._stubs["update_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/UpdateEnvironment", + request_serializer=environment.UpdateEnvironmentRequest.serialize, + response_deserializer=environment.Environment.deserialize, + ) + return self._stubs["update_environment"] + + @property + def delete_environment( + self, + ) -> Callable[[environment.DeleteEnvironmentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete environment method over gRPC. + + Deletes the specified agent environment. + + Returns: + Callable[[~.DeleteEnvironmentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_environment" not in self._stubs: + self._stubs["delete_environment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/DeleteEnvironment", + request_serializer=environment.DeleteEnvironmentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_environment"] + + @property + def get_environment_history( + self, + ) -> Callable[ + [environment.GetEnvironmentHistoryRequest], + Awaitable[environment.EnvironmentHistory], + ]: + r"""Return a callable for the get environment history method over gRPC. + + Gets the history of the specified environment. + + Returns: + Callable[[~.GetEnvironmentHistoryRequest], + Awaitable[~.EnvironmentHistory]]: + 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_environment_history" not in self._stubs: + self._stubs["get_environment_history"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Environments/GetEnvironmentHistory", + request_serializer=environment.GetEnvironmentHistoryRequest.serialize, + response_deserializer=environment.EnvironmentHistory.deserialize, + ) + return self._stubs["get_environment_history"] + __all__ = ("EnvironmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py new file mode 100644 index 000000000..6bade52dd --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import FulfillmentsClient +from .async_client import FulfillmentsAsyncClient + +__all__ = ( + "FulfillmentsClient", + "FulfillmentsAsyncClient", +) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py new file mode 100644 index 000000000..c00a671be --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/async_client.py @@ -0,0 +1,349 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport +from .client import FulfillmentsClient + + +class FulfillmentsAsyncClient: + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + """ + + _client: FulfillmentsClient + + DEFAULT_ENDPOINT = FulfillmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = FulfillmentsClient.DEFAULT_MTLS_ENDPOINT + + fulfillment_path = staticmethod(FulfillmentsClient.fulfillment_path) + parse_fulfillment_path = staticmethod(FulfillmentsClient.parse_fulfillment_path) + common_billing_account_path = staticmethod( + FulfillmentsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + FulfillmentsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(FulfillmentsClient.common_folder_path) + parse_common_folder_path = staticmethod(FulfillmentsClient.parse_common_folder_path) + common_organization_path = staticmethod(FulfillmentsClient.common_organization_path) + parse_common_organization_path = staticmethod( + FulfillmentsClient.parse_common_organization_path + ) + common_project_path = staticmethod(FulfillmentsClient.common_project_path) + parse_common_project_path = staticmethod( + FulfillmentsClient.parse_common_project_path + ) + common_location_path = staticmethod(FulfillmentsClient.common_location_path) + parse_common_location_path = staticmethod( + FulfillmentsClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_info.__func__(FulfillmentsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsAsyncClient: The constructed client. + """ + return FulfillmentsClient.from_service_account_file.__func__(FulfillmentsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Return the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(FulfillmentsClient).get_transport_class, type(FulfillmentsClient) + ) + + def __init__( + self, + *, + credentials: ga_credentials.Credentials = None, + transport: Union[str, FulfillmentsTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the fulfillments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.FulfillmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = FulfillmentsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest`): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (:class:`str`): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + 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.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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 = fulfillment.GetFulfillmentRequest(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_fulfillment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest`): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (:class:`google.cloud.dialogflow_v2beta1.types.Fulfillment`): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_fulfillment, + 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( + (("fulfillment.name", request.fulfillment.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FulfillmentsAsyncClient",) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py new file mode 100644 index 000000000..214cecf33 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/client.py @@ -0,0 +1,526 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import FulfillmentsGrpcTransport +from .transports.grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +class FulfillmentsClientMeta(type): + """Metaclass for the Fulfillments client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] + _transport_registry["grpc"] = FulfillmentsGrpcTransport + _transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[FulfillmentsTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class FulfillmentsClient(metaclass=FulfillmentsClientMeta): + """Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + FulfillmentsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> FulfillmentsTransport: + """Return the transport used by the client instance. + + Returns: + FulfillmentsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def fulfillment_path(project: str,) -> str: + """Return a fully-qualified fulfillment string.""" + return "projects/{project}/agent/fulfillment".format(project=project,) + + @staticmethod + def parse_fulfillment_path(path: str) -> Dict[str, str]: + """Parse a fulfillment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/agent/fulfillment$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, FulfillmentsTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the fulfillments client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, FulfillmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, FulfillmentsTransport): + # transport is a FulfillmentsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def get_fulfillment( + self, + request: fulfillment.GetFulfillmentRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> fulfillment.Fulfillment: + r"""Retrieves the fulfillment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetFulfillmentRequest): + The request object. The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + name (str): + Required. The name of the fulfillment. Supported + formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + 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.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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 fulfillment.GetFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, fulfillment.GetFulfillmentRequest): + request = fulfillment.GetFulfillmentRequest(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_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_fulfillment( + self, + request: gcd_fulfillment.UpdateFulfillmentRequest = None, + *, + fulfillment: gcd_fulfillment.Fulfillment = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_fulfillment.Fulfillment: + r"""Updates the fulfillment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateFulfillmentRequest): + The request object. The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + This corresponds to the ``fulfillment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. If the mask is not + present, all fields will be updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Fulfillment: + By default, your agent responds to a matched intent with a static response. + As an alternative, you can provide a more dynamic + response by using fulfillment. When you enable + fulfillment for an intent, Dialogflow responds to + that intent by calling a service that you define. For + example, if an end-user wants to schedule a haircut + on Friday, your service can check your database and + respond to the end-user with availability information + for Friday. + + For more information, see the [fulfillment + guide](\ https://cloud.google.com/dialogflow/docs/fulfillment-overview). + + """ + # 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([fulfillment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_fulfillment.UpdateFulfillmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_fulfillment.UpdateFulfillmentRequest): + request = gcd_fulfillment.UpdateFulfillmentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if fulfillment is not None: + request.fulfillment = fulfillment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_fulfillment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("fulfillment.name", request.fulfillment.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("FulfillmentsClient",) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py new file mode 100644 index 000000000..d822b662b --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import FulfillmentsTransport +from .grpc import FulfillmentsGrpcTransport +from .grpc_asyncio import FulfillmentsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[FulfillmentsTransport]] +_transport_registry["grpc"] = FulfillmentsGrpcTransport +_transport_registry["grpc_asyncio"] = FulfillmentsGrpcAsyncIOTransport + +__all__ = ( + "FulfillmentsTransport", + "FulfillmentsGrpcTransport", + "FulfillmentsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py new file mode 100644 index 000000000..6df113cd3 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/base.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class FulfillmentsTransport(abc.ABC): + """Abstract transport class for Fulfillments.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # 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. + self._wrapped_methods = { + self.get_fulfillment: gapic_v1.method.wrap_method( + self.get_fulfillment, default_timeout=None, client_info=client_info, + ), + self.update_fulfillment: gapic_v1.method.wrap_method( + self.update_fulfillment, default_timeout=None, client_info=client_info, + ), + } + + @property + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], + Union[fulfillment.Fulfillment, Awaitable[fulfillment.Fulfillment]], + ]: + raise NotImplementedError() + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Union[gcd_fulfillment.Fulfillment, Awaitable[gcd_fulfillment.Fulfillment]], + ]: + raise NotImplementedError() + + +__all__ = ("FulfillmentsTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py new file mode 100644 index 000000000..d2b8cc1b9 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO + + +class FulfillmentsGrpcTransport(FulfillmentsTransport): + """gRPC backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def get_fulfillment( + self, + ) -> Callable[[fulfillment.GetFulfillmentRequest], fulfillment.Fulfillment]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + ~.Fulfillment]: + 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_fulfillment" not in self._stubs: + self._stubs["get_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment", + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs["get_fulfillment"] + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], gcd_fulfillment.Fulfillment + ]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + ~.Fulfillment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fulfillment" not in self._stubs: + self._stubs["update_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment", + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs["update_fulfillment"] + + +__all__ = ("FulfillmentsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py new file mode 100644 index 000000000..fb9f19f76 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/fulfillments/transports/grpc_asyncio.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from .base import FulfillmentsTransport, DEFAULT_CLIENT_INFO +from .grpc import FulfillmentsGrpcTransport + + +class FulfillmentsGrpcAsyncIOTransport(FulfillmentsTransport): + """gRPC AsyncIO backend transport for Fulfillments. + + Service for managing + [Fulfillments][google.cloud.dialogflow.v2beta1.Fulfillment]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + 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, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_fulfillment( + self, + ) -> Callable[ + [fulfillment.GetFulfillmentRequest], Awaitable[fulfillment.Fulfillment] + ]: + r"""Return a callable for the get fulfillment method over gRPC. + + Retrieves the fulfillment. + + Returns: + Callable[[~.GetFulfillmentRequest], + Awaitable[~.Fulfillment]]: + 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_fulfillment" not in self._stubs: + self._stubs["get_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Fulfillments/GetFulfillment", + request_serializer=fulfillment.GetFulfillmentRequest.serialize, + response_deserializer=fulfillment.Fulfillment.deserialize, + ) + return self._stubs["get_fulfillment"] + + @property + def update_fulfillment( + self, + ) -> Callable[ + [gcd_fulfillment.UpdateFulfillmentRequest], + Awaitable[gcd_fulfillment.Fulfillment], + ]: + r"""Return a callable for the update fulfillment method over gRPC. + + Updates the fulfillment. + + Returns: + Callable[[~.UpdateFulfillmentRequest], + Awaitable[~.Fulfillment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_fulfillment" not in self._stubs: + self._stubs["update_fulfillment"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Fulfillments/UpdateFulfillment", + request_serializer=gcd_fulfillment.UpdateFulfillmentRequest.serialize, + response_deserializer=gcd_fulfillment.Fulfillment.deserialize, + ) + return self._stubs["update_fulfillment"] + + +__all__ = ("FulfillmentsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/intents/__init__.py b/google/cloud/dialogflow_v2beta1/services/intents/__init__.py index 8719a9b64..5a2c263cf 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/intents/async_client.py b/google/cloud/dialogflow_v2beta1/services/intents/async_client.py index 023b4d49d..1b588a705 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport from .client import IntentsClient @@ -57,25 +54,20 @@ class IntentsAsyncClient: parse_context_path = staticmethod(IntentsClient.parse_context_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) @@ -127,7 +119,7 @@ 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, @@ -164,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = IntentsClient( credentials=credentials, transport=transport, @@ -206,7 +197,6 @@ async def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -236,7 +226,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 if language_code is not None: @@ -303,7 +292,6 @@ async def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -339,7 +327,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 if language_code is not None: @@ -407,7 +394,6 @@ async def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -443,7 +429,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: @@ -476,7 +461,7 @@ async def update_intent( request: gcd_intent.UpdateIntentRequest = None, *, intent: gcd_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -510,7 +495,6 @@ async def update_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +530,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: @@ -605,7 +588,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. @@ -626,7 +608,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 @@ -697,7 +678,6 @@ async def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -728,7 +708,6 @@ async def batch_update_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -758,7 +737,7 @@ async def batch_update_intents( response, self._client._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -800,7 +779,6 @@ async def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -840,10 +818,8 @@ async def batch_delete_intents( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent - if intents: request.intents.extend(intents) @@ -868,8 +844,8 @@ async def batch_delete_intents( 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/dialogflow_v2beta1/services/intents/client.py b/google/cloud/dialogflow_v2beta1/services/intents/client.py index 392e2d270..cd71c75cb 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/client.py +++ b/google/cloud/dialogflow_v2beta1/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 @@ -38,10 +36,9 @@ from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import IntentsGrpcTransport from .transports.grpc_asyncio import IntentsGrpcAsyncIOTransport @@ -253,7 +250,7 @@ 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, @@ -397,7 +394,6 @@ def list_intents( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -429,10 +425,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 if language_code is not None: @@ -495,7 +489,6 @@ def get_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -533,10 +526,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 if language_code is not None: @@ -600,7 +591,6 @@ def create_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -638,10 +628,8 @@ def create_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.CreateIntentRequest): request = gcd_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: @@ -670,7 +658,7 @@ def update_intent( request: gcd_intent.UpdateIntentRequest = None, *, intent: gcd_intent.Intent = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, language_code: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, @@ -704,7 +692,6 @@ def update_intent( This corresponds to the ``language_code`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +729,8 @@ def update_intent( # there are no flattened fields. if not isinstance(request, gcd_intent.UpdateIntentRequest): request = gcd_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: @@ -800,7 +785,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. @@ -823,10 +807,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 @@ -893,7 +875,6 @@ def batch_update_intents( This corresponds to the ``intent_batch_inline`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -926,10 +907,8 @@ def batch_update_intents( # there are no flattened fields. if not isinstance(request, intent.BatchUpdateIntentsRequest): request = intent.BatchUpdateIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intent_batch_uri is not None: @@ -955,7 +934,7 @@ def batch_update_intents( response, self._transport.operations_client, intent.BatchUpdateIntentsResponse, - metadata_type=struct.Struct, + metadata_type=struct_pb2.Struct, ) # Done; return the response. @@ -997,7 +976,6 @@ def batch_delete_intents( This corresponds to the ``intents`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1039,10 +1017,8 @@ def batch_delete_intents( # there are no flattened fields. if not isinstance(request, intent.BatchDeleteIntentsRequest): request = intent.BatchDeleteIntentsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if intents is not None: @@ -1065,8 +1041,8 @@ def batch_delete_intents( 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/dialogflow_v2beta1/services/intents/pagers.py b/google/cloud/dialogflow_v2beta1/services/intents/pagers.py index 7a8547bd6..8fb78a6a2 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/pagers.py +++ b/google/cloud/dialogflow_v2beta1/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, diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py index 41fde33b5..974a58103 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/intents/transports/base.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py index b49fd88d1..ff39e5c0d 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -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 IntentsTransport(abc.ABC): """Abstract transport class for Intents.""" @@ -50,21 +60,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 @@ -73,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -148,65 +208,61 @@ def operations_client(self) -> operations_v1.OperationsClient: @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[ [gcd_intent.CreateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_intent.Intent]], ]: raise NotImplementedError() @property def update_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_intent.UpdateIntentRequest], - typing.Union[gcd_intent.Intent, typing.Awaitable[gcd_intent.Intent]], + Union[gcd_intent.Intent, Awaitable[gcd_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() @property def batch_update_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchUpdateIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_delete_intents( self, - ) -> typing.Callable[ + ) -> Callable[ [intent.BatchDeleteIntentsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py index 792e437cc..a1b2ec128 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -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 IntentsTransport, 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 @@ -180,7 +178,7 @@ def __init__( 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,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, ) @@ -345,7 +345,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 and its direct or @@ -365,14 +365,14 @@ def delete_intent(self) -> Callable[[intent.DeleteIntentRequest], empty.Empty]: self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchUpdateIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -394,14 +394,14 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], operations.Operation]: + ) -> Callable[[intent.BatchDeleteIntentsRequest], operations_pb2.Operation]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -423,7 +423,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py index f8cfe4546..101c3b56a 100644 --- a/google/cloud/dialogflow_v2beta1/services/intents/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent -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 IntentsTransport, DEFAULT_CLIENT_INFO from .grpc import IntentsGrpcTransport @@ -58,7 +55,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, @@ -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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -355,7 +354,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 and its direct or @@ -375,14 +374,16 @@ def delete_intent( self._stubs["delete_intent"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/DeleteIntent", request_serializer=intent.DeleteIntentRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_intent"] @property def batch_update_intents( self, - ) -> Callable[[intent.BatchUpdateIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchUpdateIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch update intents method over gRPC. Updates/Creates multiple intents in the specified agent. @@ -404,14 +405,16 @@ def batch_update_intents( self._stubs["batch_update_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchUpdateIntents", request_serializer=intent.BatchUpdateIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_update_intents"] @property def batch_delete_intents( self, - ) -> Callable[[intent.BatchDeleteIntentsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [intent.BatchDeleteIntentsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the batch delete intents method over gRPC. Deletes intents in the specified agent. @@ -433,7 +436,7 @@ def batch_delete_intents( self._stubs["batch_delete_intents"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.Intents/BatchDeleteIntents", request_serializer=intent.BatchDeleteIntentsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["batch_delete_intents"] diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py index be24a37d1..24204c982 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/__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 KnowledgeBasesClient from .async_client import KnowledgeBasesAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py index dfefff910..d6e92abcd 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport from .client import KnowledgeBasesClient @@ -52,31 +49,26 @@ class KnowledgeBasesAsyncClient: parse_knowledge_base_path = staticmethod( KnowledgeBasesClient.parse_knowledge_base_path ) - common_billing_account_path = staticmethod( KnowledgeBasesClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( KnowledgeBasesClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(KnowledgeBasesClient.common_folder_path) parse_common_folder_path = staticmethod( KnowledgeBasesClient.parse_common_folder_path ) - common_organization_path = staticmethod( KnowledgeBasesClient.common_organization_path ) parse_common_organization_path = staticmethod( KnowledgeBasesClient.parse_common_organization_path ) - common_project_path = staticmethod(KnowledgeBasesClient.common_project_path) parse_common_project_path = staticmethod( KnowledgeBasesClient.parse_common_project_path ) - common_location_path = staticmethod(KnowledgeBasesClient.common_location_path) parse_common_location_path = staticmethod( KnowledgeBasesClient.parse_common_location_path @@ -130,7 +122,7 @@ def transport(self) -> KnowledgeBasesTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, KnowledgeBasesTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -167,7 +159,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = KnowledgeBasesClient( credentials=credentials, transport=transport, @@ -201,7 +192,6 @@ async def list_knowledge_bases( 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. @@ -231,7 +221,6 @@ async def list_knowledge_bases( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -287,7 +276,6 @@ async def get_knowledge_base( 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. @@ -324,7 +312,6 @@ async def get_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -382,7 +369,6 @@ async def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not 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 +405,6 @@ async def create_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -471,7 +456,6 @@ async def delete_knowledge_base( 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. @@ -492,7 +476,6 @@ async def delete_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -520,7 +503,7 @@ async def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = 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]] = (), @@ -549,7 +532,6 @@ async def update_knowledge_base( 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. @@ -586,7 +568,6 @@ async def update_knowledge_base( # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py index 366e4f7ad..4dd609838 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/client.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .transports.grpc import KnowledgeBasesGrpcTransport from .transports.grpc_asyncio import KnowledgeBasesGrpcAsyncIOTransport @@ -236,7 +233,7 @@ 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, KnowledgeBasesTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -372,7 +369,6 @@ def list_knowledge_bases( 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. @@ -404,10 +400,8 @@ def list_knowledge_bases( # there are no flattened fields. if not isinstance(request, knowledge_base.ListKnowledgeBasesRequest): request = knowledge_base.ListKnowledgeBasesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -459,7 +453,6 @@ def get_knowledge_base( 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,10 +491,8 @@ def get_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.GetKnowledgeBaseRequest): request = knowledge_base.GetKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -555,7 +546,6 @@ def create_knowledge_base( This corresponds to the ``knowledge_base`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -594,10 +584,8 @@ def create_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.CreateKnowledgeBaseRequest): request = gcd_knowledge_base.CreateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if knowledge_base is not None: @@ -645,7 +633,6 @@ def delete_knowledge_base( 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. @@ -668,10 +655,8 @@ def delete_knowledge_base( # there are no flattened fields. if not isinstance(request, knowledge_base.DeleteKnowledgeBaseRequest): request = knowledge_base.DeleteKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -695,7 +680,7 @@ def update_knowledge_base( request: gcd_knowledge_base.UpdateKnowledgeBaseRequest = None, *, knowledge_base: gcd_knowledge_base.KnowledgeBase = 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]] = (), @@ -724,7 +709,6 @@ def update_knowledge_base( 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. @@ -763,10 +747,8 @@ def update_knowledge_base( # there are no flattened fields. if not isinstance(request, gcd_knowledge_base.UpdateKnowledgeBaseRequest): request = gcd_knowledge_base.UpdateKnowledgeBaseRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if knowledge_base is not None: request.knowledge_base = knowledge_base if update_mask is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py index 32d735175..3ceaafb05 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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, diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py index a3ac400b0..38da4326d 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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/dialogflow_v2beta1/services/knowledge_bases/transports/base.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py index 900d39a5f..23af5591d 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -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 KnowledgeBasesTransport(abc.ABC): """Abstract transport class for KnowledgeBases.""" @@ -48,21 +58,24 @@ class KnowledgeBasesTransport(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,7 +84,7 @@ 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): @@ -85,29 +98,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -139,11 +199,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_knowledge_bases( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.ListKnowledgeBasesRequest], - typing.Union[ + Union[ knowledge_base.ListKnowledgeBasesResponse, - typing.Awaitable[knowledge_base.ListKnowledgeBasesResponse], + Awaitable[knowledge_base.ListKnowledgeBasesResponse], ], ]: raise NotImplementedError() @@ -151,22 +211,20 @@ def list_knowledge_bases( @property def get_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.GetKnowledgeBaseRequest], - typing.Union[ - knowledge_base.KnowledgeBase, typing.Awaitable[knowledge_base.KnowledgeBase] - ], + Union[knowledge_base.KnowledgeBase, Awaitable[knowledge_base.KnowledgeBase]], ]: raise NotImplementedError() @property def create_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.CreateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() @@ -174,20 +232,20 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [knowledge_base.DeleteKnowledgeBaseRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def update_knowledge_base( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_knowledge_base.UpdateKnowledgeBaseRequest], - typing.Union[ + Union[ gcd_knowledge_base.KnowledgeBase, - typing.Awaitable[gcd_knowledge_base.KnowledgeBase], + Awaitable[gcd_knowledge_base.KnowledgeBase], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py index 563d0d737..72979a176 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, 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 @@ -177,7 +175,7 @@ def __init__( 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, @@ -208,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, ) @@ -322,7 +322,7 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty.Empty]: + ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], empty_pb2.Empty]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -344,7 +344,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py index 589b6cf50..3194691bb 100644 --- a/google/cloud/dialogflow_v2beta1/services/knowledge_bases/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/knowledge_bases/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.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import KnowledgeBasesTransport, DEFAULT_CLIENT_INFO from .grpc import KnowledgeBasesGrpcTransport @@ -56,7 +53,7 @@ class KnowledgeBasesGrpcAsyncIOTransport(KnowledgeBasesTransport): 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, @@ -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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -327,7 +326,9 @@ def create_knowledge_base( @property def delete_knowledge_base( self, - ) -> Callable[[knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty.Empty]]: + ) -> Callable[ + [knowledge_base.DeleteKnowledgeBaseRequest], Awaitable[empty_pb2.Empty] + ]: r"""Return a callable for the delete knowledge base method over gRPC. Deletes the specified knowledge base. @@ -349,7 +350,7 @@ def delete_knowledge_base( self._stubs["delete_knowledge_base"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.KnowledgeBases/DeleteKnowledgeBase", request_serializer=knowledge_base.DeleteKnowledgeBaseRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_knowledge_base"] diff --git a/google/cloud/dialogflow_v2beta1/services/participants/__init__.py b/google/cloud/dialogflow_v2beta1/services/participants/__init__.py index 9ebfb1f70..942327781 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/__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 ParticipantsClient from .async_client import ParticipantsAsyncClient diff --git a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py b/google/cloud/dialogflow_v2beta1/services/participants/async_client.py index ac4e64e35..2b3e0c761 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/async_client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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.dialogflow_v2beta1.services.participants import pagers from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant from google.cloud.dialogflow_v2beta1.types import session -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 ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport from .client import ParticipantsClient @@ -63,27 +60,22 @@ class ParticipantsAsyncClient: parse_session_entity_type_path = staticmethod( ParticipantsClient.parse_session_entity_type_path ) - common_billing_account_path = staticmethod( ParticipantsClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ParticipantsClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ParticipantsClient.common_folder_path) parse_common_folder_path = staticmethod(ParticipantsClient.parse_common_folder_path) - common_organization_path = staticmethod(ParticipantsClient.common_organization_path) parse_common_organization_path = staticmethod( ParticipantsClient.parse_common_organization_path ) - common_project_path = staticmethod(ParticipantsClient.common_project_path) parse_common_project_path = staticmethod( ParticipantsClient.parse_common_project_path ) - common_location_path = staticmethod(ParticipantsClient.common_location_path) parse_common_location_path = staticmethod( ParticipantsClient.parse_common_location_path @@ -137,7 +129,7 @@ def transport(self) -> ParticipantsTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, ParticipantsTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -174,7 +166,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ParticipantsClient( credentials=credentials, transport=transport, @@ -211,7 +202,6 @@ async def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -238,7 +228,6 @@ async def create_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -286,7 +275,6 @@ async def get_participant( 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. @@ -313,7 +301,6 @@ async def get_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -361,7 +348,6 @@ async def list_participants( 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. @@ -391,7 +377,6 @@ async def list_participants( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -426,7 +411,7 @@ async def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = 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]] = (), @@ -449,7 +434,6 @@ async def update_participant( 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. @@ -476,7 +460,6 @@ async def update_participant( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -519,8 +502,8 @@ async def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (:class:`google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest`): @@ -546,7 +529,6 @@ async def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -573,7 +555,6 @@ async def analyze_content( # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -641,7 +622,6 @@ async def suggest_articles( 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. @@ -668,7 +648,6 @@ async def suggest_articles( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -716,7 +695,6 @@ async def suggest_faq_answers( 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. @@ -743,7 +721,6 @@ async def suggest_faq_answers( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -791,7 +768,6 @@ async def suggest_smart_replies( 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. @@ -818,7 +794,6 @@ async def suggest_smart_replies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -861,7 +836,7 @@ async def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in @@ -875,7 +850,6 @@ async def list_suggestions( request (:class:`google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest`): The request object. The request message for [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -892,7 +866,6 @@ async def list_suggestions( """ # Create or coerce a protobuf request object. - request = participant.ListSuggestionsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -949,7 +922,6 @@ async def compile_suggestion( request (:class:`google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest`): The request object. The request message for [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -963,7 +935,6 @@ async def compile_suggestion( """ # Create or coerce a protobuf request object. - request = participant.CompileSuggestionRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/dialogflow_v2beta1/services/participants/client.py b/google/cloud/dialogflow_v2beta1/services/participants/client.py index ae9ace66c..dbf1a16c7 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/client.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant from google.cloud.dialogflow_v2beta1.types import session -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 ParticipantsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ParticipantsGrpcTransport from .transports.grpc_asyncio import ParticipantsGrpcAsyncIOTransport @@ -313,7 +310,7 @@ 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, ParticipantsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, @@ -452,7 +449,6 @@ def create_participant( This corresponds to the ``participant`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -481,10 +477,8 @@ def create_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.CreateParticipantRequest): request = gcd_participant.CreateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent if participant is not None: @@ -528,7 +522,6 @@ def get_participant( 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,10 +550,8 @@ def get_participant( # there are no flattened fields. if not isinstance(request, participant.GetParticipantRequest): request = participant.GetParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -604,7 +595,6 @@ def list_participants( 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. @@ -636,10 +626,8 @@ def list_participants( # there are no flattened fields. if not isinstance(request, participant.ListParticipantsRequest): request = participant.ListParticipantsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -670,7 +658,7 @@ def update_participant( request: gcd_participant.UpdateParticipantRequest = None, *, participant: gcd_participant.Participant = 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]] = (), @@ -693,7 +681,6 @@ def update_participant( 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. @@ -722,10 +709,8 @@ def update_participant( # there are no flattened fields. if not isinstance(request, gcd_participant.UpdateParticipantRequest): request = gcd_participant.UpdateParticipantRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if update_mask is not None: @@ -764,8 +749,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Args: request (google.cloud.dialogflow_v2beta1.types.AnalyzeContentRequest): @@ -791,7 +776,6 @@ def analyze_content( This corresponds to the ``event_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -820,10 +804,8 @@ def analyze_content( # there are no flattened fields. if not isinstance(request, gcd_participant.AnalyzeContentRequest): request = gcd_participant.AnalyzeContentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if participant is not None: request.participant = participant if text_input is not None: @@ -880,7 +862,6 @@ def suggest_articles( 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. @@ -909,10 +890,8 @@ def suggest_articles( # there are no flattened fields. if not isinstance(request, participant.SuggestArticlesRequest): request = participant.SuggestArticlesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -956,7 +935,6 @@ def suggest_faq_answers( 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. @@ -985,10 +963,8 @@ def suggest_faq_answers( # there are no flattened fields. if not isinstance(request, participant.SuggestFaqAnswersRequest): request = participant.SuggestFaqAnswersRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1032,7 +1008,6 @@ def suggest_smart_replies( 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. @@ -1061,10 +1036,8 @@ def suggest_smart_replies( # there are no flattened fields. if not isinstance(request, participant.SuggestSmartRepliesRequest): request = participant.SuggestSmartRepliesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1103,7 +1076,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in @@ -1117,7 +1090,6 @@ def list_suggestions( request (google.cloud.dialogflow_v2beta1.types.ListSuggestionsRequest): The request object. The request message for [Participants.ListSuggestions][google.cloud.dialogflow.v2beta1.Participants.ListSuggestions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1134,7 +1106,6 @@ def list_suggestions( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a participant.ListSuggestionsRequest. # There's no risk of modifying the input as we've already verified @@ -1192,7 +1163,6 @@ def compile_suggestion( request (google.cloud.dialogflow_v2beta1.types.CompileSuggestionRequest): The request object. The request message for [Participants.CompileSuggestion][google.cloud.dialogflow.v2beta1.Participants.CompileSuggestion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1206,7 +1176,6 @@ def compile_suggestion( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a participant.CompileSuggestionRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/dialogflow_v2beta1/services/participants/pagers.py b/google/cloud/dialogflow_v2beta1/services/participants/pagers.py index e2b2278e8..c9aeeaa2f 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/pagers.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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, diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py index 91a4cec1c..522813c1c 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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/dialogflow_v2beta1/services/participants/transports/base.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py index 6c63884a8..10e1fa8b9 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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 ParticipantsTransport(abc.ABC): """Abstract transport class for Participants.""" @@ -47,21 +57,24 @@ class ParticipantsTransport(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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -128,7 +188,9 @@ 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, @@ -156,33 +218,29 @@ def _prep_wrapped_messages(self, client_info): @property def create_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.CreateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def get_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.GetParticipantRequest], - typing.Union[ - participant.Participant, typing.Awaitable[participant.Participant] - ], + Union[participant.Participant, Awaitable[participant.Participant]], ]: raise NotImplementedError() @property def list_participants( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListParticipantsRequest], - typing.Union[ + Union[ participant.ListParticipantsResponse, - typing.Awaitable[participant.ListParticipantsResponse], + Awaitable[participant.ListParticipantsResponse], ], ]: raise NotImplementedError() @@ -190,22 +248,20 @@ def list_participants( @property def update_participant( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.UpdateParticipantRequest], - typing.Union[ - gcd_participant.Participant, typing.Awaitable[gcd_participant.Participant] - ], + Union[gcd_participant.Participant, Awaitable[gcd_participant.Participant]], ]: raise NotImplementedError() @property def analyze_content( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_participant.AnalyzeContentRequest], - typing.Union[ + Union[ gcd_participant.AnalyzeContentResponse, - typing.Awaitable[gcd_participant.AnalyzeContentResponse], + Awaitable[gcd_participant.AnalyzeContentResponse], ], ]: raise NotImplementedError() @@ -213,11 +269,11 @@ def analyze_content( @property def suggest_articles( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestArticlesRequest], - typing.Union[ + Union[ participant.SuggestArticlesResponse, - typing.Awaitable[participant.SuggestArticlesResponse], + Awaitable[participant.SuggestArticlesResponse], ], ]: raise NotImplementedError() @@ -225,11 +281,11 @@ def suggest_articles( @property def suggest_faq_answers( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestFaqAnswersRequest], - typing.Union[ + Union[ participant.SuggestFaqAnswersResponse, - typing.Awaitable[participant.SuggestFaqAnswersResponse], + Awaitable[participant.SuggestFaqAnswersResponse], ], ]: raise NotImplementedError() @@ -237,11 +293,11 @@ def suggest_faq_answers( @property def suggest_smart_replies( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.SuggestSmartRepliesRequest], - typing.Union[ + Union[ participant.SuggestSmartRepliesResponse, - typing.Awaitable[participant.SuggestSmartRepliesResponse], + Awaitable[participant.SuggestSmartRepliesResponse], ], ]: raise NotImplementedError() @@ -249,11 +305,11 @@ def suggest_smart_replies( @property def list_suggestions( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.ListSuggestionsRequest], - typing.Union[ + Union[ participant.ListSuggestionsResponse, - typing.Awaitable[participant.ListSuggestionsResponse], + Awaitable[participant.ListSuggestionsResponse], ], ]: raise NotImplementedError() @@ -261,11 +317,11 @@ def list_suggestions( @property def compile_suggestion( self, - ) -> typing.Callable[ + ) -> Callable[ [participant.CompileSuggestionRequest], - typing.Union[ + Union[ participant.CompileSuggestionResponse, - typing.Awaitable[participant.CompileSuggestionResponse], + Awaitable[participant.CompileSuggestionResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py index 04560ca1e..4822f6de4 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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,21 +13,19 @@ # 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.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - from .base import ParticipantsTransport, 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 @@ -176,7 +174,7 @@ def __init__( 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, @@ -207,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, ) @@ -346,8 +346,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -481,7 +481,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py index ad713f7d5..8e9b88110 100644 --- a/google/cloud/dialogflow_v2beta1/services/participants/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/services/participants/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,22 +13,20 @@ # 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.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant - from .base import ParticipantsTransport, DEFAULT_CLIENT_INFO from .grpc import ParticipantsGrpcTransport @@ -55,7 +52,7 @@ class ParticipantsGrpcAsyncIOTransport(ParticipantsTransport): 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, @@ -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 @@ -168,7 +168,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -356,8 +355,8 @@ def analyze_content( example) message from a participant into the conversation. Note: Always use agent versions for production traffic sent to - virtual agents. See [Versions and - environments(https://cloud.google.com/dialogflow/es/docs/agents-versions). + virtual agents. See `Versions and + environments `__. Returns: Callable[[~.AnalyzeContentRequest], @@ -494,7 +493,7 @@ def list_suggestions( fetch auto generated suggestions in real-time, while the conversation with an end user is in progress. The functionality is implemented in terms of the `list - pagination `__ + pagination `__ design pattern. The client app should use the ``next_page_token`` field to fetch the next batch of suggestions. ``suggestions`` are sorted by ``create_time`` in diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py index c0dca267f..cbd406b49 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/session_entity_types/async_client.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py index 1fac133d4..8878a39be 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.services.session_entity_types import pagers @@ -34,8 +32,7 @@ from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_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 @@ -136,7 +128,7 @@ 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, @@ -173,7 +165,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionEntityTypesClient( credentials=credentials, transport=transport, @@ -217,7 +208,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. @@ -247,7 +237,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 @@ -312,7 +301,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. @@ -347,7 +335,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 @@ -417,7 +404,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. @@ -452,7 +438,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: @@ -483,7 +468,7 @@ async def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_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]] = (), @@ -511,7 +496,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. @@ -546,7 +530,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: @@ -609,7 +592,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. @@ -630,7 +612,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/dialogflow_v2beta1/services/session_entity_types/client.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py index 37ff5e1b2..c56b5d71c 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.types import ( session_entity_type as gcd_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 @@ -242,7 +239,7 @@ 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, @@ -388,7 +385,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. @@ -420,10 +416,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 @@ -486,7 +480,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. @@ -523,10 +516,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 @@ -592,7 +583,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. @@ -631,10 +621,8 @@ def create_session_entity_type( request, gcd_session_entity_type.CreateSessionEntityTypeRequest ): request = gcd_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: @@ -663,7 +651,7 @@ def update_session_entity_type( request: gcd_session_entity_type.UpdateSessionEntityTypeRequest = None, *, session_entity_type: gcd_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]] = (), @@ -691,7 +679,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. @@ -730,10 +717,8 @@ def update_session_entity_type( request, gcd_session_entity_type.UpdateSessionEntityTypeRequest ): request = gcd_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: @@ -794,7 +779,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. @@ -817,10 +801,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/dialogflow_v2beta1/services/session_entity_types/pagers.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py index f92cbf966..009a68602 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/pagers.py +++ b/google/cloud/dialogflow_v2beta1/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, diff --git a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py index 606f91160..633fd32cb 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/session_entity_types/transports/base.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py index e3e62fc17..ad4cbed37 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.types import session_entity_type from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_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,7 +86,7 @@ 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): @@ -87,29 +100,76 @@ 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=self._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=self._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 + # 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. self._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[ [gcd_session_entity_type.CreateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_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[ [gcd_session_entity_type.UpdateSessionEntityTypeRequest], - typing.Union[ + Union[ gcd_session_entity_type.SessionEntityType, - typing.Awaitable[gcd_session_entity_type.SessionEntityType], + Awaitable[gcd_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/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py index 6ef126d94..93f87cf86 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.types import ( session_entity_type as gcd_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 @@ -179,7 +177,7 @@ def __init__( 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, @@ -210,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, ) @@ -361,7 +361,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. @@ -383,7 +385,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py index 10e5ecdfd..57b303dc5 100644 --- a/google/cloud/dialogflow_v2beta1/services/session_entity_types/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.types import ( session_entity_type as gcd_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, @@ -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 @@ -171,7 +171,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -366,7 +365,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. @@ -389,7 +388,7 @@ def delete_session_entity_type( self._stubs["delete_session_entity_type"] = self.grpc_channel.unary_unary( "/google.cloud.dialogflow.v2beta1.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/dialogflow_v2beta1/services/sessions/__init__.py b/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py index 3b2a59a9d..0adeafb97 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/sessions/async_client.py b/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py index c62121f7d..a96a7c1a3 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/async_client.py +++ b/google/cloud/dialogflow_v2beta1/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,17 +29,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.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport from .client import SessionsClient @@ -71,25 +68,20 @@ class SessionsAsyncClient: parse_session_entity_type_path = staticmethod( SessionsClient.parse_session_entity_type_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) @@ -141,7 +133,7 @@ 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, @@ -178,7 +170,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = SessionsClient( credentials=credentials, transport=transport, @@ -253,7 +244,6 @@ async def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -280,7 +270,6 @@ async def detect_intent( # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/client.py b/google/cloud/dialogflow_v2beta1/services/sessions/client.py index 9800ee01b..6b5a65294 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/client.py +++ b/google/cloud/dialogflow_v2beta1/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,8 +43,7 @@ from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session -from google.rpc import status_pb2 as status # type: ignore - +from google.rpc import status_pb2 # type: ignore from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO from .transports.grpc import SessionsGrpcTransport from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport @@ -307,7 +304,7 @@ 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, @@ -484,7 +481,6 @@ def detect_intent( This corresponds to the ``query_input`` field on the ``request`` instance; if ``request`` is provided, this should not 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,10 +509,8 @@ def detect_intent( # there are no flattened fields. if not isinstance(request, gcd_session.DetectIntentRequest): request = gcd_session.DetectIntentRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if session is not None: request.session = session if query_input is not None: diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py index 0ca6c76ea..db0f7d045 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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/dialogflow_v2beta1/services/sessions/transports/base.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py index 24431128f..a2804b91d 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/base.py +++ b/google/cloud/dialogflow_v2beta1/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,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.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( @@ -38,6 +37,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.""" @@ -47,21 +57,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 @@ -70,7 +83,7 @@ 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): @@ -84,29 +97,76 @@ 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=self._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=self._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 + # 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. self._wrapped_methods = { @@ -116,7 +176,9 @@ 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, @@ -132,11 +194,11 @@ def _prep_wrapped_messages(self, client_info): @property def detect_intent( self, - ) -> typing.Callable[ + ) -> Callable[ [gcd_session.DetectIntentRequest], - typing.Union[ + Union[ gcd_session.DetectIntentResponse, - typing.Awaitable[gcd_session.DetectIntentResponse], + Awaitable[gcd_session.DetectIntentResponse], ], ]: raise NotImplementedError() @@ -144,11 +206,11 @@ def detect_intent( @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() diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py index c1fc1907c..aa5a28ca9 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc.py +++ b/google/cloud/dialogflow_v2beta1/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,21 +13,19 @@ # 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.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - from .base import SessionsTransport, 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 @@ -178,7 +176,7 @@ def __init__( 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, @@ -209,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, ) diff --git a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py index ad283b9d5..7389490de 100644 --- a/google/cloud/dialogflow_v2beta1/services/sessions/transports/grpc_asyncio.py +++ b/google/cloud/dialogflow_v2beta1/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,22 +13,20 @@ # 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.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import session as gcd_session - from .base import SessionsTransport, DEFAULT_CLIENT_INFO from .grpc import SessionsGrpcTransport @@ -57,7 +54,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, @@ -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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/dialogflow_v2beta1/services/versions/__init__.py b/google/cloud/dialogflow_v2beta1/services/versions/__init__.py new file mode 100644 index 000000000..586be1818 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import VersionsClient +from .async_client import VersionsAsyncClient + +__all__ = ( + "VersionsClient", + "VersionsAsyncClient", +) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/async_client.py b/google/cloud/dialogflow_v2beta1/services/versions/async_client.py new file mode 100644 index 000000000..a629f162a --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/async_client.py @@ -0,0 +1,625 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_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 + + +class VersionsAsyncClient: + """Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + """ + + _client: VersionsClient + + DEFAULT_ENDPOINT = VersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = VersionsClient.DEFAULT_MTLS_ENDPOINT + + 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. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_info.__func__(VersionsAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsAsyncClient: The constructed client. + """ + return VersionsClient.from_service_account_file.__func__(VersionsAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Return the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(VersionsClient).get_transport_class, type(VersionsClient) + ) + + def __init__( + self, + *, + 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. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = VersionsClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsAsyncPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.ListVersionsRequest`): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (:class:`str`): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsAsyncPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = version.ListVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListVersionsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.GetVersionRequest`): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (:class:`str`): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 = version.GetVersionRequest(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_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.CreateVersionRequest`): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (:class:`str`): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to create. + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_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: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest`): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (:class:`google.cloud.dialogflow_v2beta1.types.Version`): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = gcd_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: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_version, + 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( + (("version.name", request.version.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (:class:`google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest`): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (:class:`str`): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = version.DeleteVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("VersionsAsyncClient",) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/client.py b/google/cloud/dialogflow_v2beta1/services/versions/client.py new file mode 100644 index 000000000..84ece9a2a --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/client.py @@ -0,0 +1,810 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import field_mask_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 + + +class VersionsClientMeta(type): + """Metaclass for the Versions client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] + _transport_registry["grpc"] = VersionsGrpcTransport + _transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[VersionsTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class VersionsClient(metaclass=VersionsClientMeta): + """Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + VersionsClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> VersionsTransport: + """Return the transport used by the client instance. + + Returns: + VersionsTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def version_path(project: str, version: str,) -> str: + """Return a fully-qualified version string.""" + return "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) + + @staticmethod + def parse_version_path(path: str) -> Dict[str, str]: + """Parse a version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/agent/versions/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[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. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, VersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + client_cert_source_func = ( + mtls.default_client_cert_source() if is_mtls else None + ) + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, VersionsTransport): + # transport is a VersionsTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def list_versions( + self, + request: version.ListVersionsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListVersionsPager: + r"""Returns the list of all versions of the specified + agent. + + Args: + request (google.cloud.dialogflow_v2beta1.types.ListVersionsRequest): + The request object. The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.services.versions.pagers.ListVersionsPager: + The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a version.ListVersionsRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListVersionsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_version( + self, + request: version.GetVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> version.Version: + r"""Retrieves the specified agent version. + + Args: + request (google.cloud.dialogflow_v2beta1.types.GetVersionRequest): + The request object. The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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 version.GetVersionRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_version( + self, + request: gcd_version.CreateVersionRequest = None, + *, + parent: str = None, + version: gcd_version.Version = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Args: + request (google.cloud.dialogflow_v2beta1.types.CreateVersionRequest): + The request object. The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + 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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.CreateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.CreateVersionRequest): + request = gcd_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: + request.version = version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_version( + self, + request: gcd_version.UpdateVersionRequest = None, + *, + version: gcd_version.Version = None, + update_mask: field_mask_pb2.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_version.Version: + r"""Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Args: + request (google.cloud.dialogflow_v2beta1.types.UpdateVersionRequest): + The request object. The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + + This corresponds to the ``version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which + fields get updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.dialogflow_v2beta1.types.Version: + You can create multiple versions of your agent and publish them to separate + environments. + + When you edit an agent, you are editing the draft + agent. At any point, you can save the draft agent as + an agent version, which is an immutable snapshot of + your agent. + + When you save the draft agent, it is published to the + default environment. When you create agent versions, + you can publish them to custom environments. You can + create a variety of custom environments for: + + - testing + - development + - production + - etc. + + For more information, see the [versions and + environments + guide](\ https://cloud.google.com/dialogflow/docs/agents-versions). + + """ + # 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([version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a gcd_version.UpdateVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, gcd_version.UpdateVersionRequest): + request = gcd_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: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("version.name", request.version.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_version( + self, + request: version.DeleteVersionRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Delete the specified agent version. + + Args: + request (google.cloud.dialogflow_v2beta1.types.DeleteVersionRequest): + The request object. The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a version.DeleteVersionRequest. + # There's no risk of modifying the input as we've already verified + # 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 + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("VersionsClient",) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/pagers.py b/google/cloud/dialogflow_v2beta1/services/versions/pagers.py new file mode 100644 index 000000000..05970d62c --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/pagers.py @@ -0,0 +1,155 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterable, + Awaitable, + Callable, + Iterable, + Sequence, + Tuple, + Optional, +) + +from google.cloud.dialogflow_v2beta1.types import version + + +class ListVersionsPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., version.ListVersionsResponse], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[version.Version]: + for page in self.pages: + yield from page.versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListVersionsAsyncPager: + """A pager for iterating through ``list_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListVersions`` requests and continue to iterate + through the ``versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2beta1.types.ListVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[version.ListVersionsResponse]], + request: version.ListVersionsRequest, + response: version.ListVersionsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.dialogflow_v2beta1.types.ListVersionsRequest): + The initial request object. + response (google.cloud.dialogflow_v2beta1.types.ListVersionsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = version.ListVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[version.ListVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[version.Version]: + async def async_generator(): + async for page in self.pages: + for response in page.versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py new file mode 100644 index 000000000..c5a42a0e8 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import VersionsTransport +from .grpc import VersionsGrpcTransport +from .grpc_asyncio import VersionsGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[VersionsTransport]] +_transport_registry["grpc"] = VersionsGrpcTransport +_transport_registry["grpc_asyncio"] = VersionsGrpcAsyncIOTransport + +__all__ = ( + "VersionsTransport", + "VersionsGrpcTransport", + "VersionsGrpcAsyncIOTransport", +) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py new file mode 100644 index 000000000..82d478c05 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/base.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-dialogflow", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + + +class VersionsTransport(abc.ABC): + """Abstract transport class for Versions.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + + # Save the scopes. + self._scopes = scopes or self.AUTH_SCOPES + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # 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. + self._wrapped_methods = { + self.list_versions: gapic_v1.method.wrap_method( + self.list_versions, default_timeout=None, client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, default_timeout=None, client_info=client_info, + ), + self.create_version: gapic_v1.method.wrap_method( + self.create_version, default_timeout=None, client_info=client_info, + ), + self.update_version: gapic_v1.method.wrap_method( + self.update_version, default_timeout=None, client_info=client_info, + ), + self.delete_version: gapic_v1.method.wrap_method( + self.delete_version, default_timeout=None, client_info=client_info, + ), + } + + @property + def list_versions( + self, + ) -> Callable[ + [version.ListVersionsRequest], + Union[version.ListVersionsResponse, Awaitable[version.ListVersionsResponse]], + ]: + raise NotImplementedError() + + @property + def get_version( + self, + ) -> Callable[ + [version.GetVersionRequest], Union[version.Version, Awaitable[version.Version]] + ]: + raise NotImplementedError() + + @property + def create_version( + self, + ) -> Callable[ + [gcd_version.CreateVersionRequest], + Union[gcd_version.Version, Awaitable[gcd_version.Version]], + ]: + raise NotImplementedError() + + @property + def update_version( + self, + ) -> Callable[ + [gcd_version.UpdateVersionRequest], + Union[gcd_version.Version, Awaitable[gcd_version.Version]], + ]: + raise NotImplementedError() + + @property + def delete_version( + self, + ) -> Callable[ + [version.DeleteVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + +__all__ = ("VersionsTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py new file mode 100644 index 000000000..7d150e364 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO + + +class VersionsGrpcTransport(VersionsTransport): + """gRPC backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_versions( + self, + ) -> Callable[[version.ListVersionsRequest], version.ListVersionsResponse]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + ~.ListVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_versions" not in self._stubs: + self._stubs["list_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/ListVersions", + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs["list_versions"] + + @property + def get_version(self) -> Callable[[version.GetVersionRequest], version.Version]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + ~.Version]: + 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_version" not in self._stubs: + self._stubs["get_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/GetVersion", + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs["get_version"] + + @property + def create_version( + self, + ) -> Callable[[gcd_version.CreateVersionRequest], gcd_version.Version]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_version" not in self._stubs: + self._stubs["create_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/CreateVersion", + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["create_version"] + + @property + def update_version( + self, + ) -> Callable[[gcd_version.UpdateVersionRequest], gcd_version.Version]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + ~.Version]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_version" not in self._stubs: + self._stubs["update_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion", + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["update_version"] + + @property + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_version" not in self._stubs: + self._stubs["delete_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion", + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_version"] + + +__all__ = ("VersionsGrpcTransport",) diff --git a/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py new file mode 100644 index 000000000..0223a30ab --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/services/versions/transports/grpc_asyncio.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.protobuf import empty_pb2 # type: ignore +from .base import VersionsTransport, DEFAULT_CLIENT_INFO +from .grpc import VersionsGrpcTransport + + +class VersionsGrpcAsyncIOTransport(VersionsTransport): + """gRPC AsyncIO backend transport for Versions. + + Service for managing + [Versions][google.cloud.dialogflow.v2beta1.Version]. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + 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, + quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "dialogflow.googleapis.com", + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_versions( + self, + ) -> Callable[ + [version.ListVersionsRequest], Awaitable[version.ListVersionsResponse] + ]: + r"""Return a callable for the list versions method over gRPC. + + Returns the list of all versions of the specified + agent. + + Returns: + Callable[[~.ListVersionsRequest], + Awaitable[~.ListVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_versions" not in self._stubs: + self._stubs["list_versions"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/ListVersions", + request_serializer=version.ListVersionsRequest.serialize, + response_deserializer=version.ListVersionsResponse.deserialize, + ) + return self._stubs["list_versions"] + + @property + def get_version( + self, + ) -> Callable[[version.GetVersionRequest], Awaitable[version.Version]]: + r"""Return a callable for the get version method over gRPC. + + Retrieves the specified agent version. + + Returns: + Callable[[~.GetVersionRequest], + Awaitable[~.Version]]: + 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_version" not in self._stubs: + self._stubs["get_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/GetVersion", + request_serializer=version.GetVersionRequest.serialize, + response_deserializer=version.Version.deserialize, + ) + return self._stubs["get_version"] + + @property + def create_version( + self, + ) -> Callable[[gcd_version.CreateVersionRequest], Awaitable[gcd_version.Version]]: + r"""Return a callable for the create version method over gRPC. + + Creates an agent version. + The new version points to the agent instance in the + "default" environment. + + Returns: + Callable[[~.CreateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_version" not in self._stubs: + self._stubs["create_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/CreateVersion", + request_serializer=gcd_version.CreateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["create_version"] + + @property + def update_version( + self, + ) -> Callable[[gcd_version.UpdateVersionRequest], Awaitable[gcd_version.Version]]: + r"""Return a callable for the update version method over gRPC. + + Updates the specified agent version. + Note that this method does not allow you to update the + state of the agent the given version points to. It + allows you to update only mutable properties of the + version resource. + + Returns: + Callable[[~.UpdateVersionRequest], + Awaitable[~.Version]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_version" not in self._stubs: + self._stubs["update_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/UpdateVersion", + request_serializer=gcd_version.UpdateVersionRequest.serialize, + response_deserializer=gcd_version.Version.deserialize, + ) + return self._stubs["update_version"] + + @property + def delete_version( + self, + ) -> Callable[[version.DeleteVersionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete version method over gRPC. + + Delete the specified agent version. + + Returns: + Callable[[~.DeleteVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_version" not in self._stubs: + self._stubs["delete_version"] = self.grpc_channel.unary_unary( + "/google.cloud.dialogflow.v2beta1.Versions/DeleteVersion", + request_serializer=version.DeleteVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_version"] + + +__all__ = ("VersionsGrpcAsyncIOTransport",) diff --git a/google/cloud/dialogflow_v2beta1/types/__init__.py b/google/cloud/dialogflow_v2beta1/types/__init__.py index 1b5381fee..efe17b293 100644 --- a/google/cloud/dialogflow_v2beta1/types/__init__.py +++ b/google/cloud/dialogflow_v2beta1/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, DeleteAgentRequest, @@ -125,9 +123,21 @@ UpdateEntityTypeRequest, ) from .environment import ( + CreateEnvironmentRequest, + DeleteEnvironmentRequest, Environment, + EnvironmentHistory, + GetEnvironmentHistoryRequest, + GetEnvironmentRequest, ListEnvironmentsRequest, ListEnvironmentsResponse, + TextToSpeechSettings, + UpdateEnvironmentRequest, +) +from .fulfillment import ( + Fulfillment, + GetFulfillmentRequest, + UpdateFulfillmentRequest, ) from .gcs import ( GcsSource, @@ -219,6 +229,15 @@ ValidationError, ValidationResult, ) +from .version import ( + CreateVersionRequest, + DeleteVersionRequest, + GetVersionRequest, + ListVersionsRequest, + ListVersionsResponse, + UpdateVersionRequest, + Version, +) from .webhook import ( OriginalDetectIntentRequest, WebhookRequest, @@ -319,9 +338,19 @@ "ListEntityTypesRequest", "ListEntityTypesResponse", "UpdateEntityTypeRequest", + "CreateEnvironmentRequest", + "DeleteEnvironmentRequest", "Environment", + "EnvironmentHistory", + "GetEnvironmentHistoryRequest", + "GetEnvironmentRequest", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "TextToSpeechSettings", + "UpdateEnvironmentRequest", + "Fulfillment", + "GetFulfillmentRequest", + "UpdateFulfillmentRequest", "GcsSource", "GcsSources", "HumanAgentAssistantEvent", @@ -398,6 +427,13 @@ "UpdateSessionEntityTypeRequest", "ValidationError", "ValidationResult", + "CreateVersionRequest", + "DeleteVersionRequest", + "GetVersionRequest", + "ListVersionsRequest", + "ListVersionsResponse", + "UpdateVersionRequest", + "Version", "OriginalDetectIntentRequest", "WebhookRequest", "WebhookResponse", diff --git a/google/cloud/dialogflow_v2beta1/types/agent.py b/google/cloud/dialogflow_v2beta1/types/agent.py index 980d7cb91..fc51cfd93 100644 --- a/google/cloud/dialogflow_v2beta1/types/agent.py +++ b/google/cloud/dialogflow_v2beta1/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,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( @@ -135,28 +132,17 @@ class Tier(proto.Enum): TIER_ENTERPRISE = 2 TIER_ENTERPRISE_PLUS = 3 - parent = 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) - - enable_logging = proto.Field(proto.BOOL, number=8) - + parent = 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,) + enable_logging = proto.Field(proto.BOOL, number=8,) match_mode = proto.Field(proto.ENUM, number=9, enum=MatchMode,) - - classification_threshold = proto.Field(proto.FLOAT, number=10) - + classification_threshold = proto.Field(proto.FLOAT, number=10,) api_version = proto.Field(proto.ENUM, number=14, enum=ApiVersion,) - tier = proto.Field(proto.ENUM, number=15, enum=Tier,) @@ -171,7 +157,7 @@ class GetAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SetAgentRequest(proto.Message): @@ -187,8 +173,9 @@ class SetAgentRequest(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): @@ -202,12 +189,11 @@ class DeleteAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class SubAgent(proto.Message): r"""Contains basic configuration for a sub-agent. - Attributes: project (str): Required. The project of this agent. Format: @@ -219,9 +205,8 @@ class SubAgent(proto.Message): draft environment if ``environment`` is not set. """ - project = proto.Field(proto.STRING, number=1) - - environment = proto.Field(proto.STRING, number=2) + project = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.STRING, number=2,) class SearchAgentsRequest(proto.Message): @@ -242,11 +227,9 @@ class SearchAgentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class SearchAgentsResponse(proto.Message): @@ -268,8 +251,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 TrainAgentRequest(proto.Message): @@ -283,7 +265,7 @@ class TrainAgentRequest(proto.Message): ``projects//locations/``. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ExportAgentRequest(proto.Message): @@ -303,9 +285,8 @@ class ExportAgentRequest(proto.Message): the serialized agent is returned inline. """ - parent = proto.Field(proto.STRING, number=1) - - agent_uri = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + agent_uri = proto.Field(proto.STRING, number=2,) class ExportAgentResponse(proto.Message): @@ -321,9 +302,8 @@ class ExportAgentResponse(proto.Message): Zip compressed 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 ImportAgentRequest(proto.Message): @@ -343,11 +323,9 @@ class ImportAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = 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") + parent = 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",) class RestoreAgentRequest(proto.Message): @@ -367,11 +345,9 @@ class RestoreAgentRequest(proto.Message): Zip compressed raw byte content for agent. """ - parent = 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") + parent = 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",) class GetValidationResultRequest(proto.Message): @@ -392,9 +368,8 @@ class GetValidationResultRequest(proto.Message): before they can be used. """ - parent = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/answer_record.py b/google/cloud/dialogflow_v2beta1/types/answer_record.py index 3661084a4..b645483eb 100644 --- a/google/cloud/dialogflow_v2beta1/types/answer_record.py +++ b/google/cloud/dialogflow_v2beta1/types/answer_record.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.dialogflow_v2beta1.types import participant -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( @@ -84,10 +81,8 @@ class AnswerRecord(proto.Message): assistant. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) answer_feedback = proto.Field(proto.MESSAGE, number=3, message="AnswerFeedback",) - agent_assistant_record = proto.Field( proto.MESSAGE, number=4, oneof="record", message="AgentAssistantRecord", ) @@ -95,7 +90,6 @@ class AnswerRecord(proto.Message): class AgentAssistantRecord(proto.Message): r"""Represents a record of a human agent assistant answer. - Attributes: article_suggestion_answer (google.cloud.dialogflow_v2beta1.types.ArticleAnswer): Output only. The article suggestion answer. @@ -106,7 +100,6 @@ class AgentAssistantRecord(proto.Message): article_suggestion_answer = proto.Field( proto.MESSAGE, number=5, oneof="answer", message=participant.ArticleAnswer, ) - faq_answer = proto.Field( proto.MESSAGE, number=6, oneof="answer", message=participant.FaqAnswer, ) @@ -143,26 +136,22 @@ class CorrectnessLevel(proto.Enum): FULLY_CORRECT = 3 correctness_level = proto.Field(proto.ENUM, number=1, enum=CorrectnessLevel,) - agent_assistant_detail_feedback = proto.Field( proto.MESSAGE, number=2, oneof="detail_feedback", message="AgentAssistantFeedback", ) - - clicked = proto.Field(proto.BOOL, number=3) - - click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - displayed = proto.Field(proto.BOOL, number=4) - - display_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + clicked = proto.Field(proto.BOOL, number=3,) + click_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + displayed = proto.Field(proto.BOOL, number=4,) + display_time = proto.Field( + proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp, + ) class AgentAssistantFeedback(proto.Message): r"""Detail feedback of Agent Assistant result. - Attributes: answer_relevance (google.cloud.dialogflow_v2beta1.types.AgentAssistantFeedback.AnswerRelevance): Optional. Whether or not the suggested answer is relevant. @@ -218,7 +207,6 @@ class DocumentEfficiency(proto.Enum): class SummarizationFeedback(proto.Message): r"""Feedback for conversation summarization. - Attributes: start_timestamp (google.protobuf.timestamp_pb2.Timestamp): Timestamp when composing of the summary @@ -230,21 +218,16 @@ class SummarizationFeedback(proto.Message): """ start_timestamp = proto.Field( - proto.MESSAGE, number=1, message=timestamp.Timestamp, + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) - submit_timestamp = proto.Field( - proto.MESSAGE, number=2, message=timestamp.Timestamp, + proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - - summary_text = proto.Field(proto.STRING, number=3) + summary_text = proto.Field(proto.STRING, number=3,) answer_relevance = proto.Field(proto.ENUM, number=1, enum=AnswerRelevance,) - document_correctness = proto.Field(proto.ENUM, number=2, enum=DocumentCorrectness,) - document_efficiency = proto.Field(proto.ENUM, number=3, enum=DocumentEfficiency,) - summarization_feedback = proto.Field( proto.MESSAGE, number=4, message=SummarizationFeedback, ) @@ -260,7 +243,7 @@ class GetAnswerRecordRequest(proto.Message): ``projects//locations//answerRecords/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListAnswerRecordsRequest(proto.Message): @@ -284,11 +267,9 @@ class ListAnswerRecordsRequest(proto.Message): listing on the next page. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class ListAnswerRecordsResponse(proto.Message): @@ -313,8 +294,7 @@ def raw_page(self): answer_records = proto.RepeatedField( proto.MESSAGE, number=1, message="AnswerRecord", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateAnswerRecordRequest(proto.Message): @@ -330,8 +310,9 @@ class UpdateAnswerRecordRequest(proto.Message): """ answer_record = proto.Field(proto.MESSAGE, number=1, message="AnswerRecord",) - - 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, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/audio_config.py b/google/cloud/dialogflow_v2beta1/types/audio_config.py index fda8a8e73..737f9c059 100644 --- a/google/cloud/dialogflow_v2beta1/types/audio_config.py +++ b/google/cloud/dialogflow_v2beta1/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( @@ -153,14 +150,12 @@ class SpeechContext(proto.Message): binary search. """ - phrases = proto.RepeatedField(proto.STRING, number=1) - - boost = proto.Field(proto.FLOAT, number=2) + phrases = proto.RepeatedField(proto.STRING, number=1,) + boost = proto.Field(proto.FLOAT, number=2,) class SpeechWordInfo(proto.Message): r"""Information for a word recognized by the speech recognizer. - Attributes: word (str): The word this info is for. @@ -187,13 +182,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): @@ -280,31 +272,21 @@ class InputAudioConfig(proto.Message): """ audio_encoding = proto.Field(proto.ENUM, number=1, enum="AudioEncoding",) - - sample_rate_hertz = proto.Field(proto.INT32, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - enable_word_info = proto.Field(proto.BOOL, number=13) - - phrase_hints = proto.RepeatedField(proto.STRING, number=4) - + sample_rate_hertz = proto.Field(proto.INT32, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + enable_word_info = proto.Field(proto.BOOL, number=13,) + phrase_hints = proto.RepeatedField(proto.STRING, number=4,) speech_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message="SpeechContext", ) - - model = proto.Field(proto.STRING, number=7) - + 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) - - disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14) + single_utterance = proto.Field(proto.BOOL, number=8,) + disable_no_speech_recognized_event = proto.Field(proto.BOOL, number=14,) 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 @@ -326,14 +308,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 @@ -367,14 +347,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",) @@ -403,9 +379,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", ) @@ -413,7 +387,6 @@ class OutputAudioConfig(proto.Message): class TelephonyDtmfEvents(proto.Message): r"""A wrapper of repeated TelephonyDtmf digits. - Attributes: dtmf_events (Sequence[google.cloud.dialogflow_v2beta1.types.TelephonyDtmf]): A sequence of TelephonyDtmf digits. diff --git a/google/cloud/dialogflow_v2beta1/types/context.py b/google/cloud/dialogflow_v2beta1/types/context.py index d0179a6a2..8b4d02a29 100644 --- a/google/cloud/dialogflow_v2beta1/types/context.py +++ b/google/cloud/dialogflow_v2beta1/types/context.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 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( @@ -108,11 +105,9 @@ class Context(proto.Message): Else: parameter value """ - name = proto.Field(proto.STRING, number=1) - - lifespan_count = proto.Field(proto.INT32, number=2) - - parameters = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + name = proto.Field(proto.STRING, number=1,) + lifespan_count = proto.Field(proto.INT32, number=2,) + parameters = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) class ListContextsRequest(proto.Message): @@ -142,11 +137,9 @@ class ListContextsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListContextsResponse(proto.Message): @@ -168,8 +161,7 @@ def raw_page(self): return self contexts = proto.RepeatedField(proto.MESSAGE, number=1, message="Context",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetContextRequest(proto.Message): @@ -191,7 +183,7 @@ class GetContextRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateContextRequest(proto.Message): @@ -216,8 +208,7 @@ class CreateContextRequest(proto.Message): Required. The context to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) context = proto.Field(proto.MESSAGE, number=2, message="Context",) @@ -234,8 +225,9 @@ class UpdateContextRequest(proto.Message): """ context = proto.Field(proto.MESSAGE, number=1, message="Context",) - - 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 DeleteContextRequest(proto.Message): @@ -258,7 +250,7 @@ class DeleteContextRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class DeleteAllContextsRequest(proto.Message): @@ -281,7 +273,7 @@ class DeleteAllContextsRequest(proto.Message): specified, we assume default '-' user. """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/conversation.py b/google/cloud/dialogflow_v2beta1/types/conversation.py index 11ffff26c..ba8089cf0 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation.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.dialogflow_v2beta1.types import participant -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -105,21 +102,15 @@ class ConversationStage(proto.Enum): VIRTUAL_AGENT_STAGE = 1 HUMAN_ASSIST_STAGE = 2 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) lifecycle_state = proto.Field(proto.ENUM, number=2, enum=LifecycleState,) - - conversation_profile = proto.Field(proto.STRING, number=3) - + conversation_profile = proto.Field(proto.STRING, number=3,) phone_number = proto.Field( proto.MESSAGE, number=4, message="ConversationPhoneNumber", ) - conversation_stage = proto.Field(proto.ENUM, number=7, enum=ConversationStage,) - - start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) class ConversationPhoneNumber(proto.Message): @@ -132,7 +123,7 @@ class ConversationPhoneNumber(proto.Message): this conversation. """ - phone_number = proto.Field(proto.STRING, number=3) + phone_number = proto.Field(proto.STRING, number=3,) class CreateConversationRequest(proto.Message): @@ -162,11 +153,9 @@ class CreateConversationRequest(proto.Message): a project to better ensure uniqueness. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation = proto.Field(proto.MESSAGE, number=2, message="Conversation",) - - conversation_id = proto.Field(proto.STRING, number=3) + conversation_id = proto.Field(proto.STRING, number=3,) class ListConversationsRequest(proto.Message): @@ -208,13 +197,10 @@ class ListConversationsRequest(proto.Message): Filtering `__. """ - 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 ListConversationsResponse(proto.Message): @@ -238,8 +224,7 @@ def raw_page(self): conversations = proto.RepeatedField( proto.MESSAGE, number=1, message="Conversation", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationRequest(proto.Message): @@ -252,7 +237,7 @@ class GetConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CompleteConversationRequest(proto.Message): @@ -266,7 +251,7 @@ class CompleteConversationRequest(proto.Message): ``projects//locations//conversations/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateMessageRequest(proto.Message): @@ -284,8 +269,7 @@ class CreateMessageRequest(proto.Message): is required. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) message = proto.Field(proto.MESSAGE, number=2, message=participant.Message,) @@ -305,8 +289,7 @@ class BatchCreateMessagesRequest(proto.Message): [Message.create_time][google.cloud.dialogflow.v2beta1.Message.create_time]. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) requests = proto.RepeatedField( proto.MESSAGE, number=2, message="CreateMessageRequest", ) @@ -341,7 +324,7 @@ class ListMessagesRequest(proto.Message): supported. ``create_time`` only support milliseconds accuracy. E.g., ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > 2017-01-15T01:30:15.01Z``. + ``create_time > "2017-01-15T01:30:15.01Z"``. For more information about filtering, see `API Filtering `__. @@ -354,13 +337,10 @@ class ListMessagesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + filter = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListMessagesResponse(proto.Message): @@ -386,8 +366,7 @@ def raw_page(self): messages = proto.RepeatedField( proto.MESSAGE, number=1, message=participant.Message, ) - - 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/dialogflow_v2beta1/types/conversation_event.py b/google/cloud/dialogflow_v2beta1/types/conversation_event.py index a9091e3af..dee158441 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation_event.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation_event.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.dialogflow_v2beta1.types import participant -from google.rpc import status_pb2 as status # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -54,12 +51,9 @@ class Type(proto.Enum): NEW_MESSAGE = 5 UNRECOVERABLE_ERROR = 4 - conversation = proto.Field(proto.STRING, number=1) - + conversation = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum=Type,) - - error_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - + error_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) new_message_payload = proto.Field( proto.MESSAGE, number=4, oneof="payload", message=participant.Message, ) diff --git a/google/cloud/dialogflow_v2beta1/types/conversation_profile.py b/google/cloud/dialogflow_v2beta1/types/conversation_profile.py index 4d1c17775..0e9d1a396 100644 --- a/google/cloud/dialogflow_v2beta1/types/conversation_profile.py +++ b/google/cloud/dialogflow_v2beta1/types/conversation_profile.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.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import participant -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( @@ -68,6 +65,8 @@ class ConversationProfile(proto.Message): with this profile. human_agent_handoff_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig): Configuration for connecting to a live agent. + Currently, this feature is not general + available, please contact Google to get access. notification_config (google.cloud.dialogflow_v2beta1.types.NotificationConfig): Configuration for publishing conversation lifecycle events. @@ -87,46 +86,38 @@ class ConversationProfile(proto.Message): for all non en-us languages. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - create_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=12, message=timestamp.Timestamp,) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=11, message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, number=12, message=timestamp_pb2.Timestamp, + ) automated_agent_config = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentConfig", ) - human_agent_assistant_config = proto.Field( proto.MESSAGE, number=4, message="HumanAgentAssistantConfig", ) - human_agent_handoff_config = proto.Field( proto.MESSAGE, number=5, message="HumanAgentHandoffConfig", ) - notification_config = proto.Field( proto.MESSAGE, number=6, message="NotificationConfig", ) - logging_config = proto.Field(proto.MESSAGE, number=7, message="LoggingConfig",) - new_message_event_notification_config = proto.Field( proto.MESSAGE, number=8, message="NotificationConfig", ) - stt_config = proto.Field( proto.MESSAGE, number=9, message=audio_config.SpeechToTextConfig, ) - - language_code = proto.Field(proto.STRING, number=10) + language_code = proto.Field(proto.STRING, number=10,) class AutomatedAgentConfig(proto.Message): r"""Defines the Automated Agent to connect to a conversation. - Attributes: agent (str): Required. ID of the Dialogflow agent environment to use. @@ -149,7 +140,7 @@ class AutomatedAgentConfig(proto.Message): environment is used. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class HumanAgentAssistantConfig(proto.Message): @@ -166,13 +157,14 @@ class HumanAgentAssistantConfig(proto.Message): end_user_suggestion_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionConfig): Configuration for agent assistance of end user participant. + Currently, this feature is not general + available, please contact Google to get access. message_analysis_config (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.MessageAnalysisConfig): Configuration for message analysis. """ class SuggestionTriggerSettings(proto.Message): r"""Settings of suggestion trigger. - Attributes: no_small_talk (bool): Do not trigger if last utterance is small @@ -182,13 +174,11 @@ class SuggestionTriggerSettings(proto.Message): utterance is END_USER. """ - no_small_talk = proto.Field(proto.BOOL, number=1) - - only_end_user = proto.Field(proto.BOOL, number=2) + no_small_talk = proto.Field(proto.BOOL, number=1,) + only_end_user = proto.Field(proto.BOOL, number=2,) class SuggestionFeatureConfig(proto.Message): r"""Config for suggestion features. - Attributes: suggestion_feature (google.cloud.dialogflow_v2beta1.types.SuggestionFeature): The suggestion feature. @@ -212,21 +202,17 @@ class SuggestionFeatureConfig(proto.Message): suggestion_feature = proto.Field( proto.MESSAGE, number=5, message=participant.SuggestionFeature, ) - - enable_event_based_suggestion = proto.Field(proto.BOOL, number=3) - + enable_event_based_suggestion = proto.Field(proto.BOOL, number=3,) suggestion_trigger_settings = proto.Field( proto.MESSAGE, number=10, message="HumanAgentAssistantConfig.SuggestionTriggerSettings", ) - query_config = proto.Field( proto.MESSAGE, number=6, message="HumanAgentAssistantConfig.SuggestionQueryConfig", ) - conversation_model_config = proto.Field( proto.MESSAGE, number=7, @@ -235,7 +221,6 @@ class SuggestionFeatureConfig(proto.Message): class SuggestionConfig(proto.Message): r"""Detail human agent assistant config. - Attributes: feature_configs (Sequence[google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionFeatureConfig]): Configuration of different suggestion @@ -260,12 +245,10 @@ class SuggestionConfig(proto.Message): number=2, message="HumanAgentAssistantConfig.SuggestionFeatureConfig", ) - - group_suggestion_responses = proto.Field(proto.BOOL, number=3) + group_suggestion_responses = proto.Field(proto.BOOL, number=3,) class SuggestionQueryConfig(proto.Message): r"""Config for suggestion query. - Attributes: knowledge_base_query_source (google.cloud.dialogflow_v2beta1.types.HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource): Query from knowledgebase. It is used by: ARTICLE_SUGGESTION, @@ -320,7 +303,7 @@ class KnowledgeBaseQuerySource(proto.Message): Currently, only one knowledge base is supported. """ - knowledge_bases = proto.RepeatedField(proto.STRING, number=1) + knowledge_bases = proto.RepeatedField(proto.STRING, number=1,) class DocumentQuerySource(proto.Message): r"""Document source settings. @@ -334,7 +317,7 @@ class DocumentQuerySource(proto.Message): Currently, only one document is supported. """ - documents = proto.RepeatedField(proto.STRING, number=1) + documents = proto.RepeatedField(proto.STRING, number=1,) class DialogflowQuerySource(proto.Message): r"""Dialogflow source setting. @@ -350,7 +333,7 @@ class DialogflowQuerySource(proto.Message): project. """ - agent = proto.Field(proto.STRING, number=1) + agent = proto.Field(proto.STRING, number=1,) class ContextFilterSettings(proto.Message): r"""Settings that determine how to filter recent conversation @@ -369,11 +352,9 @@ class ContextFilterSettings(proto.Message): are dropped. """ - drop_handoff_messages = proto.Field(proto.BOOL, number=1) - - drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2) - - drop_ivr_messages = proto.Field(proto.BOOL, number=3) + drop_handoff_messages = proto.Field(proto.BOOL, number=1,) + drop_virtual_agent_messages = proto.Field(proto.BOOL, number=2,) + drop_ivr_messages = proto.Field(proto.BOOL, number=3,) knowledge_base_query_source = proto.Field( proto.MESSAGE, @@ -381,25 +362,20 @@ class ContextFilterSettings(proto.Message): oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.KnowledgeBaseQuerySource", ) - document_query_source = proto.Field( proto.MESSAGE, number=2, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DocumentQuerySource", ) - dialogflow_query_source = proto.Field( proto.MESSAGE, number=3, oneof="query_source", message="HumanAgentAssistantConfig.SuggestionQueryConfig.DialogflowQuerySource", ) - - max_results = proto.Field(proto.INT32, number=4) - - confidence_threshold = proto.Field(proto.FLOAT, number=5) - + max_results = proto.Field(proto.INT32, number=4,) + confidence_threshold = proto.Field(proto.FLOAT, number=5,) context_filter_settings = proto.Field( proto.MESSAGE, number=7, @@ -413,11 +389,11 @@ class ConversationModelConfig(proto.Message): Attributes: model (str): - Required. Conversation model resource name. Format: + Conversation model resource name. Format: ``projects//conversationModels/``. """ - model = proto.Field(proto.STRING, number=1) + model = proto.Field(proto.STRING, number=1,) class MessageAnalysisConfig(proto.Message): r"""Configuration for analyses to run on each conversation @@ -429,6 +405,9 @@ class MessageAnalysisConfig(proto.Message): assist stage `__. If unspecified, defaults to false. + + Currently, this feature is not general available, please + contact Google to get access. enable_sentiment_analysis (bool): Enable sentiment analysis in conversation messages on `agent assist @@ -454,22 +433,18 @@ class MessageAnalysisConfig(proto.Message): [ConversationEvent.new_message_payload.SentimentAnalysisResult][google.cloud.dialogflow.v2beta1.ConversationEvent.new_message_payload]. """ - enable_entity_extraction = proto.Field(proto.BOOL, number=2) - - enable_sentiment_analysis = proto.Field(proto.BOOL, number=3) + enable_entity_extraction = proto.Field(proto.BOOL, number=2,) + enable_sentiment_analysis = proto.Field(proto.BOOL, number=3,) notification_config = proto.Field( proto.MESSAGE, number=2, message="NotificationConfig", ) - human_agent_suggestion_config = proto.Field( proto.MESSAGE, number=3, message=SuggestionConfig, ) - end_user_suggestion_config = proto.Field( proto.MESSAGE, number=4, message=SuggestionConfig, ) - message_analysis_config = proto.Field( proto.MESSAGE, number=5, message=MessageAnalysisConfig, ) @@ -478,6 +453,8 @@ class MessageAnalysisConfig(proto.Message): class HumanAgentHandoffConfig(proto.Message): r"""Defines the hand off to a live agent, typically on which external agent service provider to connect to a conversation. + Currently, this feature is not general available, please contact + Google to get access. Attributes: live_person_config (google.cloud.dialogflow_v2beta1.types.HumanAgentHandoffConfig.LivePersonConfig): @@ -497,11 +474,10 @@ class LivePersonConfig(proto.Message): you input at the login page. """ - account_number = proto.Field(proto.STRING, number=1) + account_number = proto.Field(proto.STRING, number=1,) class SalesforceLiveAgentConfig(proto.Message): r"""Configuration specific to Salesforce Live Agent. - Attributes: organization_id (str): Required. The organization ID of the @@ -518,18 +494,14 @@ class SalesforceLiveAgentConfig(proto.Message): fill in d.la4-c2-phx.salesforceliveagent.com. """ - organization_id = proto.Field(proto.STRING, number=1) - - deployment_id = proto.Field(proto.STRING, number=2) - - button_id = proto.Field(proto.STRING, number=3) - - endpoint_domain = proto.Field(proto.STRING, number=4) + organization_id = proto.Field(proto.STRING, number=1,) + deployment_id = proto.Field(proto.STRING, number=2,) + button_id = proto.Field(proto.STRING, number=3,) + endpoint_domain = proto.Field(proto.STRING, number=4,) live_person_config = proto.Field( proto.MESSAGE, number=1, oneof="agent_service", message=LivePersonConfig, ) - salesforce_live_agent_config = proto.Field( proto.MESSAGE, number=2, @@ -540,7 +512,6 @@ class SalesforceLiveAgentConfig(proto.Message): class NotificationConfig(proto.Message): r"""Defines notification behavior. - Attributes: topic (str): Name of the Pub/Sub topic to publish conversation events @@ -567,14 +538,12 @@ class MessageFormat(proto.Enum): PROTO = 1 JSON = 2 - topic = proto.Field(proto.STRING, number=1) - + topic = proto.Field(proto.STRING, number=1,) message_format = proto.Field(proto.ENUM, number=2, enum=MessageFormat,) class LoggingConfig(proto.Message): r"""Defines logging behavior for conversation lifecycle events. - Attributes: enable_stackdriver_logging (bool): Whether to log conversation events like @@ -584,7 +553,7 @@ class LoggingConfig(proto.Message): protos. """ - enable_stackdriver_logging = proto.Field(proto.BOOL, number=3) + enable_stackdriver_logging = proto.Field(proto.BOOL, number=3,) class ListConversationProfilesRequest(proto.Message): @@ -604,11 +573,9 @@ class ListConversationProfilesRequest(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 ListConversationProfilesResponse(proto.Message): @@ -633,8 +600,7 @@ def raw_page(self): conversation_profiles = proto.RepeatedField( proto.MESSAGE, number=1, message="ConversationProfile", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationProfileRequest(proto.Message): @@ -648,7 +614,7 @@ class GetConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateConversationProfileRequest(proto.Message): @@ -663,8 +629,7 @@ class CreateConversationProfileRequest(proto.Message): Required. The conversation profile to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) conversation_profile = proto.Field( proto.MESSAGE, number=2, message="ConversationProfile", ) @@ -685,8 +650,9 @@ class UpdateConversationProfileRequest(proto.Message): conversation_profile = proto.Field( proto.MESSAGE, number=1, message="ConversationProfile", ) - - 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 DeleteConversationProfileRequest(proto.Message): @@ -703,7 +669,7 @@ class DeleteConversationProfileRequest(proto.Message): ``projects//locations//conversationProfiles/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/document.py b/google/cloud/dialogflow_v2beta1/types/document.py index 3a90e221e..68a1ea238 100644 --- a/google/cloud/dialogflow_v2beta1/types/document.py +++ b/google/cloud/dialogflow_v2beta1/types/document.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.dialogflow_v2beta1.types import gcs -from google.protobuf import field_mask_pb2 as field_mask # 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 timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -128,7 +125,6 @@ class KnowledgeType(proto.Enum): class ReloadStatus(proto.Message): r"""The status of a reload attempt. - Attributes: time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time of a reload attempt. @@ -140,29 +136,19 @@ class ReloadStatus(proto.Message): or the initial load. """ - time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - + time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) status = proto.Field(proto.MESSAGE, number=2, message=gr_status.Status,) - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - mime_type = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + mime_type = proto.Field(proto.STRING, number=3,) knowledge_types = proto.RepeatedField(proto.ENUM, number=4, enum=KnowledgeType,) - - content_uri = proto.Field(proto.STRING, number=5, oneof="source") - - content = proto.Field(proto.STRING, number=6, oneof="source") - - raw_content = proto.Field(proto.BYTES, number=9, oneof="source") - - enable_auto_reload = proto.Field(proto.BOOL, number=11) - + content_uri = proto.Field(proto.STRING, number=5, oneof="source",) + content = proto.Field(proto.STRING, number=6, oneof="source",) + raw_content = proto.Field(proto.BYTES, number=9, oneof="source",) + enable_auto_reload = proto.Field(proto.BOOL, number=11,) latest_reload_status = proto.Field(proto.MESSAGE, number=12, message=ReloadStatus,) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=7) + metadata = proto.MapField(proto.STRING, proto.STRING, number=7,) class GetDocumentRequest(proto.Message): @@ -175,7 +161,7 @@ class GetDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListDocumentsRequest(proto.Message): @@ -219,13 +205,10 @@ class ListDocumentsRequest(proto.Message): Filtering `__. """ - 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 ListDocumentsResponse(proto.Message): @@ -246,8 +229,7 @@ def raw_page(self): return self documents = proto.RepeatedField(proto.MESSAGE, number=1, message="Document",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateDocumentRequest(proto.Message): @@ -267,11 +249,9 @@ class CreateDocumentRequest(proto.Message): source is Google Cloud Storage URI. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) document = proto.Field(proto.MESSAGE, number=2, message="Document",) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=3) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=3,) class ImportDocumentsRequest(proto.Message): @@ -299,22 +279,18 @@ class ImportDocumentsRequest(proto.Message): source is Google Cloud Storage URI. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=2, oneof="source", message=gcs.GcsSources, ) - document_template = proto.Field( proto.MESSAGE, number=3, message="ImportDocumentTemplate", ) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4,) class ImportDocumentTemplate(proto.Message): r"""The template used for importing documents. - Attributes: mime_type (str): Required. The MIME type of the document. @@ -329,13 +305,11 @@ class ImportDocumentTemplate(proto.Message): ``value`` of the metadata is 1024 bytes. """ - mime_type = proto.Field(proto.STRING, number=1) - + mime_type = proto.Field(proto.STRING, number=1,) knowledge_types = proto.RepeatedField( proto.ENUM, number=2, enum="Document.KnowledgeType", ) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=3) + metadata = proto.MapField(proto.STRING, proto.STRING, number=3,) class ImportDocumentsResponse(proto.Message): @@ -361,7 +335,7 @@ class DeleteDocumentRequest(proto.Message): ``projects//locations//knowledgeBases//documents/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateDocumentRequest(proto.Message): @@ -378,8 +352,9 @@ class UpdateDocumentRequest(proto.Message): """ document = proto.Field(proto.MESSAGE, number=1, message="Document",) - - 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 KnowledgeOperationMetadata(proto.Message): @@ -420,13 +395,11 @@ class ReloadDocumentRequest(proto.Message): source is Google Cloud Storage URI. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) gcs_source = proto.Field( proto.MESSAGE, number=3, oneof="source", message=gcs.GcsSource, ) - - import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4) + import_gcs_custom_metadata = proto.Field(proto.BOOL, number=4,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/entity_type.py b/google/cloud/dialogflow_v2beta1/types/entity_type.py index e395607b1..1143c6b55 100644 --- a/google/cloud/dialogflow_v2beta1/types/entity_type.py +++ b/google/cloud/dialogflow_v2beta1/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( @@ -100,7 +97,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 @@ -126,21 +122,15 @@ class Entity(proto.Message): ``value``. """ - value = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + value = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) + 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=6, message=Entity,) - - enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7) + enable_fuzzy_extraction = proto.Field(proto.BOOL, number=7,) class ListEntityTypesRequest(proto.Message): @@ -169,13 +159,10 @@ class ListEntityTypesRequest(proto.Message): list 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): @@ -198,8 +185,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): @@ -220,9 +206,8 @@ class GetEntityTypeRequest(proto.Message): data `__. """ - 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): @@ -246,11 +231,9 @@ class CreateEntityTypeRequest(proto.Message): data `__. """ - 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): @@ -272,10 +255,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): @@ -291,7 +274,7 @@ class DeleteEntityTypeRequest(proto.Message): - ``projects//locations//agent/entityTypes/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateEntityTypesRequest(proto.Message): @@ -325,19 +308,17 @@ class BatchUpdateEntityTypesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entity_type_batch_uri = proto.Field( - proto.STRING, number=2, oneof="entity_type_batch" + proto.STRING, number=2, oneof="entity_type_batch", ) - entity_type_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="entity_type_batch", message="EntityTypeBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) class BatchUpdateEntityTypesResponse(proto.Message): @@ -369,9 +350,8 @@ class BatchDeleteEntityTypesRequest(proto.Message): point to the same agent as ``parent``. """ - parent = proto.Field(proto.STRING, number=1) - - entity_type_names = proto.RepeatedField(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entity_type_names = proto.RepeatedField(proto.STRING, number=2,) class BatchCreateEntitiesRequest(proto.Message): @@ -395,13 +375,11 @@ class BatchCreateEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) + language_code = proto.Field(proto.STRING, number=3,) class BatchUpdateEntitiesRequest(proto.Message): @@ -428,15 +406,14 @@ class BatchUpdateEntitiesRequest(proto.Message): get updated. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) entities = proto.RepeatedField( proto.MESSAGE, number=2, message="EntityType.Entity", ) - - language_code = proto.Field(proto.STRING, number=3) - - update_mask = proto.Field(proto.MESSAGE, number=4, message=field_mask.FieldMask,) + language_code = proto.Field(proto.STRING, number=3,) + update_mask = proto.Field( + proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask, + ) class BatchDeleteEntitiesRequest(proto.Message): @@ -462,11 +439,9 @@ class BatchDeleteEntitiesRequest(proto.Message): data `__. """ - parent = proto.Field(proto.STRING, number=1) - - entity_values = proto.RepeatedField(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + entity_values = proto.RepeatedField(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) class EntityTypeBatch(proto.Message): diff --git a/google/cloud/dialogflow_v2beta1/types/environment.py b/google/cloud/dialogflow_v2beta1/types/environment.py index 9f5c887de..5ee003e2f 100644 --- a/google/cloud/dialogflow_v2beta1/types/environment.py +++ b/google/cloud/dialogflow_v2beta1/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,16 +13,28 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.cloud.dialogflow_v2beta1.types import audio_config +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package="google.cloud.dialogflow.v2beta1", - manifest={"Environment", "ListEnvironmentsRequest", "ListEnvironmentsResponse",}, + manifest={ + "Environment", + "TextToSpeechSettings", + "ListEnvironmentsRequest", + "ListEnvironmentsResponse", + "GetEnvironmentRequest", + "CreateEnvironmentRequest", + "UpdateEnvironmentRequest", + "DeleteEnvironmentRequest", + "GetEnvironmentHistoryRequest", + "EnvironmentHistory", + }, ) @@ -74,6 +85,12 @@ class Environment(proto.Message): Output only. The last update time of this environment. This field is read-only, i.e., it cannot be set by create and update methods. + text_to_speech_settings (google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings): + Optional. Text to speech settings for this + environment. + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Optional. The fulfillment settings to use for + this environment. """ class State(proto.Enum): @@ -89,15 +106,58 @@ class State(proto.Enum): LOADING = 2 RUNNING = 3 - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + agent_version = proto.Field(proto.STRING, number=3,) + state = proto.Field(proto.ENUM, number=4, enum=State,) + update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + text_to_speech_settings = proto.Field( + proto.MESSAGE, number=7, message="TextToSpeechSettings", + ) + fulfillment = proto.Field( + proto.MESSAGE, number=8, message=gcd_fulfillment.Fulfillment, + ) - description = proto.Field(proto.STRING, number=2) - agent_version = proto.Field(proto.STRING, number=3) +class TextToSpeechSettings(proto.Message): + r"""Instructs the speech synthesizer on how to generate the + output audio content. - state = proto.Field(proto.ENUM, number=4, enum=State,) + Attributes: + enable_text_to_speech (bool): + Optional. Indicates whether text to speech is + enabled. Even when this field is false, other + settings in this proto are still retained. + output_audio_encoding (google.cloud.dialogflow_v2beta1.types.OutputAudioEncoding): + Required. Audio encoding of the synthesized + audio content. + sample_rate_hertz (int): + Optional. The synthesis sample rate (in + hertz) for this audio. If not provided, then the + synthesizer will use the default sample rate + based on the audio encoding. If this is + different from the voice's natural sample rate, + then the synthesizer will honor this request by + converting to the desired sample rate (which + might result in worse audio quality). + synthesize_speech_configs (Sequence[google.cloud.dialogflow_v2beta1.types.TextToSpeechSettings.SynthesizeSpeechConfigsEntry]): + Optional. Configuration of how speech should + be synthesized, mapping from language + (https://cloud.google.com/dialogflow/docs/reference/language) + to SynthesizeSpeechConfig. + """ - update_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + enable_text_to_speech = proto.Field(proto.BOOL, number=1,) + output_audio_encoding = proto.Field( + proto.ENUM, number=2, enum=audio_config.OutputAudioEncoding, + ) + sample_rate_hertz = proto.Field(proto.INT32, number=3,) + synthesize_speech_configs = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=audio_config.SynthesizeSpeechConfig, + ) class ListEnvironmentsRequest(proto.Message): @@ -119,11 +179,9 @@ class ListEnvironmentsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + 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): @@ -146,8 +204,160 @@ def raw_page(self): return self environments = proto.RepeatedField(proto.MESSAGE, number=1, message="Environment",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironment][google.cloud.dialogflow.v2beta1.Environments.GetEnvironment]. + + Attributes: + name (str): + Required. The name of the environment. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. + + Attributes: + parent (str): + Required. The agent to create an environment for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to create. + environment_id (str): + Required. The unique id of the new + environment. + """ + + parent = proto.Field(proto.STRING, number=1,) + environment = proto.Field(proto.MESSAGE, number=2, message="Environment",) + environment_id = proto.Field(proto.STRING, number=3,) + + +class UpdateEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.UpdateEnvironment][google.cloud.dialogflow.v2beta1.Environments.UpdateEnvironment]. + + Attributes: + environment (google.cloud.dialogflow_v2beta1.types.Environment): + Required. The environment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + allow_load_to_draft_and_discard_changes (bool): + Optional. This field is used to prevent accidental overwrite + of the draft environment, which is an operation that cannot + be undone. To confirm that the caller desires this + overwrite, this field must be explicitly set to true when + updating the draft environment (environment ID = ``-``). + """ + + environment = proto.Field(proto.MESSAGE, number=1, message="Environment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + allow_load_to_draft_and_discard_changes = proto.Field(proto.BOOL, number=3,) + + +class DeleteEnvironmentRequest(proto.Message): + r"""The request message for + [Environments.DeleteEnvironment][google.cloud.dialogflow.v2beta1.Environments.DeleteEnvironment]. + + Attributes: + name (str): + Required. The name of the environment to delete. / Format: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class GetEnvironmentHistoryRequest(proto.Message): + r"""The request message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Required. The name of the environment to retrieve history + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class EnvironmentHistory(proto.Message): + r"""The response message for + [Environments.GetEnvironmentHistory][google.cloud.dialogflow.v2beta1.Environments.GetEnvironmentHistory]. + + Attributes: + parent (str): + Output only. The name of the environment this history is + for. Supported formats: + + - ``projects//agent/environments/`` + - ``projects//locations//agent/environments/`` + entries (Sequence[google.cloud.dialogflow_v2beta1.types.EnvironmentHistory.Entry]): + Output only. The list of agent environments. There will be a + maximum number of items returned based on the page_size + field in the request. + next_page_token (str): + Output only. Token to retrieve the next page + of results, or empty if there are no more + results in the list. + """ + + class Entry(proto.Message): + r"""Represents an environment history entry. + Attributes: + agent_version (str): + The agent version loaded into this + environment history entry. + description (str): + The developer-provided description for this + environment history entry. + create_time (google.protobuf.timestamp_pb2.Timestamp): + The creation time of this environment history + entry. + """ + + agent_version = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + create_time = proto.Field( + proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, + ) + + @property + def raw_page(self): + return self - next_page_token = proto.Field(proto.STRING, number=2) + parent = proto.Field(proto.STRING, number=1,) + entries = proto.RepeatedField(proto.MESSAGE, number=2, message=Entry,) + next_page_token = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/fulfillment.py b/google/cloud/dialogflow_v2beta1/types/fulfillment.py new file mode 100644 index 000000000..a77f89e38 --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/types/fulfillment.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2beta1", + manifest={"Fulfillment", "GetFulfillmentRequest", "UpdateFulfillmentRequest",}, +) + + +class Fulfillment(proto.Message): + r"""By default, your agent responds to a matched intent with a static + response. As an alternative, you can provide a more dynamic response + by using fulfillment. When you enable fulfillment for an intent, + Dialogflow responds to that intent by calling a service that you + define. For example, if an end-user wants to schedule a haircut on + Friday, your service can check your database and respond to the + end-user with availability information for Friday. + + For more information, see the `fulfillment + guide `__. + + Attributes: + name (str): + Required. The unique identifier of the fulfillment. + Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + + This field is not used for Fulfillment in an Environment. + display_name (str): + The human-readable name of the fulfillment, + unique within the agent. + This field is not used for Fulfillment in an + Environment. + generic_web_service (google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService): + Configuration for a generic web service. + enabled (bool): + Whether fulfillment is enabled. + features (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature]): + The field defines whether the fulfillment is + enabled for certain features. + """ + + class GenericWebService(proto.Message): + r"""Represents configuration for a generic web service. + Dialogflow supports two mechanisms for authentications: - Basic + authentication with username and password. + - Authentication with additional authentication headers. More + information could be found at: + https://cloud.google.com/dialogflow/docs/fulfillment-configure. + + Attributes: + uri (str): + Required. The fulfillment URI for receiving + POST requests. It must use https protocol. + username (str): + The user name for HTTP Basic authentication. + password (str): + The password for HTTP Basic authentication. + request_headers (Sequence[google.cloud.dialogflow_v2beta1.types.Fulfillment.GenericWebService.RequestHeadersEntry]): + The HTTP request headers to send together + with fulfillment requests. + is_cloud_function (bool): + Optional. Indicates if generic web service is created + through Cloud Functions integration. Defaults to false. + + is_cloud_function is deprecated. Cloud functions can be + configured by its uri as a regular web service now. + """ + + 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,) + is_cloud_function = proto.Field(proto.BOOL, number=5,) + + class Feature(proto.Message): + r"""Whether fulfillment is enabled for the specific feature. + Attributes: + type_ (google.cloud.dialogflow_v2beta1.types.Fulfillment.Feature.Type): + The type of the feature that enabled for + fulfillment. + """ + + class Type(proto.Enum): + r"""The type of the feature.""" + TYPE_UNSPECIFIED = 0 + SMALLTALK = 1 + + type_ = proto.Field(proto.ENUM, number=1, enum="Fulfillment.Feature.Type",) + + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + generic_web_service = proto.Field( + proto.MESSAGE, number=3, oneof="fulfillment", message=GenericWebService, + ) + enabled = proto.Field(proto.BOOL, number=4,) + features = proto.RepeatedField(proto.MESSAGE, number=5, message=Feature,) + + +class GetFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.GetFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.GetFulfillment]. + + Attributes: + name (str): + Required. The name of the fulfillment. Supported formats: + + - ``projects//agent/fulfillment`` + - ``projects//locations//agent/fulfillment`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class UpdateFulfillmentRequest(proto.Message): + r"""The request message for + [Fulfillments.UpdateFulfillment][google.cloud.dialogflow.v2beta1.Fulfillments.UpdateFulfillment]. + + Attributes: + fulfillment (google.cloud.dialogflow_v2beta1.types.Fulfillment): + Required. The fulfillment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + fulfillment = proto.Field(proto.MESSAGE, number=1, message="Fulfillment",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/gcs.py b/google/cloud/dialogflow_v2beta1/types/gcs.py index 17dd7573a..6905e49cc 100644 --- a/google/cloud/dialogflow_v2beta1/types/gcs.py +++ b/google/cloud/dialogflow_v2beta1/types/gcs.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 @@ -25,7 +23,6 @@ class GcsSources(proto.Message): r"""Google Cloud Storage locations for the inputs. - Attributes: uris (Sequence[str]): Required. Google Cloud Storage URIs for the @@ -35,12 +32,11 @@ class GcsSources(proto.Message): use case. """ - uris = proto.RepeatedField(proto.STRING, number=2) + uris = proto.RepeatedField(proto.STRING, number=2,) class GcsSource(proto.Message): r"""Google Cloud Storage location for single input. - Attributes: uri (str): Required. The Google Cloud Storage URIs for @@ -50,7 +46,7 @@ class GcsSource(proto.Message): use case. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py b/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py index 66d6bf2c9..b66735d32 100644 --- a/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py +++ b/google/cloud/dialogflow_v2beta1/types/human_agent_assistant_event.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import participant as gcd_participant @@ -51,10 +48,8 @@ class HumanAgentAssistantEvent(proto.Message): sets to true. """ - conversation = proto.Field(proto.STRING, number=1) - - participant = proto.Field(proto.STRING, number=3) - + conversation = proto.Field(proto.STRING, number=1,) + participant = proto.Field(proto.STRING, number=3,) suggestion_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_participant.SuggestionResult, ) diff --git a/google/cloud/dialogflow_v2beta1/types/intent.py b/google/cloud/dialogflow_v2beta1/types/intent.py index 75dea97f7..3a1e868ec 100644 --- a/google/cloud/dialogflow_v2beta1/types/intent.py +++ b/google/cloud/dialogflow_v2beta1/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,13 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import context -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( @@ -195,7 +192,6 @@ class WebhookState(proto.Enum): class TrainingPhrase(proto.Message): r"""Represents an example that the agent is trained on. - Attributes: name (str): Output only. The unique identifier of this @@ -242,7 +238,6 @@ class Type(proto.Enum): class Part(proto.Message): r"""Represents a part of a training phrase. - Attributes: text (str): Required. The text for this part. @@ -263,27 +258,20 @@ class Part(proto.Message): part with the API, you must set this to true. """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - alias = proto.Field(proto.STRING, number=3) - - user_defined = proto.Field(proto.BOOL, number=4) - - name = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + alias = proto.Field(proto.STRING, number=3,) + user_defined = proto.Field(proto.BOOL, number=4,) + name = proto.Field(proto.STRING, number=1,) type_ = proto.Field(proto.ENUM, number=2, enum="Intent.TrainingPhrase.Type",) - parts = proto.RepeatedField( proto.MESSAGE, number=3, message="Intent.TrainingPhrase.Part", ) - - times_added_count = proto.Field(proto.INT32, number=4) + times_added_count = proto.Field(proto.INT32, number=4,) class Parameter(proto.Message): r"""Represents intent parameters. - Attributes: name (str): The unique identifier of this parameter. @@ -321,25 +309,17 @@ class Parameter(proto.Message): represents a list of values. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - value = proto.Field(proto.STRING, number=3) - - default_value = proto.Field(proto.STRING, number=4) - - entity_type_display_name = proto.Field(proto.STRING, number=5) - - mandatory = proto.Field(proto.BOOL, number=6) - - prompts = proto.RepeatedField(proto.STRING, number=7) - - is_list = proto.Field(proto.BOOL, number=8) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + value = proto.Field(proto.STRING, number=3,) + default_value = proto.Field(proto.STRING, number=4,) + entity_type_display_name = proto.Field(proto.STRING, number=5,) + mandatory = proto.Field(proto.BOOL, number=6,) + prompts = proto.RepeatedField(proto.STRING, number=7,) + is_list = proto.Field(proto.BOOL, number=8,) class Message(proto.Message): r"""Corresponds to the ``Response`` field in the Dialogflow console. - Attributes: text (google.cloud.dialogflow_v2beta1.types.Intent.Message.Text): Returns a text response. @@ -413,18 +393,16 @@ class Platform(proto.Enum): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): Optional. The collection of the agent's responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class Image(proto.Message): r"""The image response message. - Attributes: image_uri (str): Optional. The public URI to an image file. @@ -434,13 +412,11 @@ class Image(proto.Message): is set for CarouselSelect. """ - image_uri = proto.Field(proto.STRING, number=1) - - accessibility_text = proto.Field(proto.STRING, number=2) + image_uri = proto.Field(proto.STRING, number=1,) + accessibility_text = proto.Field(proto.STRING, number=2,) class QuickReplies(proto.Message): r"""The quick replies response message. - Attributes: title (str): Optional. The title of the collection of @@ -449,13 +425,11 @@ class QuickReplies(proto.Message): Optional. The collection of quick replies. """ - title = proto.Field(proto.STRING, number=1) - - quick_replies = proto.RepeatedField(proto.STRING, number=2) + title = proto.Field(proto.STRING, number=1,) + quick_replies = proto.RepeatedField(proto.STRING, number=2,) class Card(proto.Message): r"""The card response message. - Attributes: title (str): Optional. The title of the card. @@ -470,7 +444,6 @@ class Card(proto.Message): class Button(proto.Message): r"""Optional. Contains information about a button. - Attributes: text (str): Optional. The text to show on the button. @@ -479,23 +452,18 @@ class Button(proto.Message): Dialogflow API or a URI to open. """ - text = proto.Field(proto.STRING, number=1) - - postback = proto.Field(proto.STRING, number=2) - - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - image_uri = proto.Field(proto.STRING, number=3) + text = proto.Field(proto.STRING, number=1,) + postback = proto.Field(proto.STRING, number=2,) + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + image_uri = proto.Field(proto.STRING, number=3,) buttons = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.Card.Button", ) class SimpleResponse(proto.Message): r"""The simple response message containing speech or text. - Attributes: text_to_speech (str): One of text_to_speech or ssml must be provided. The plain @@ -508,11 +476,9 @@ class SimpleResponse(proto.Message): Optional. The text to display. """ - text_to_speech = proto.Field(proto.STRING, number=1) - - ssml = proto.Field(proto.STRING, number=2) - - display_text = proto.Field(proto.STRING, number=3) + text_to_speech = proto.Field(proto.STRING, number=1,) + ssml = proto.Field(proto.STRING, number=2,) + display_text = proto.Field(proto.STRING, number=3,) class SimpleResponses(proto.Message): r"""The collection of simple response candidates. This message in @@ -531,7 +497,6 @@ class SimpleResponses(proto.Message): class BasicCard(proto.Message): r"""The basic card message. Useful for displaying information. - Attributes: title (str): Optional. The title of the card. @@ -548,7 +513,6 @@ class BasicCard(proto.Message): class Button(proto.Message): r"""The button object that appears at the bottom of a card. - Attributes: title (str): Required. The title of the button. @@ -559,32 +523,26 @@ class Button(proto.Message): class OpenUriAction(proto.Message): r"""Opens the given URI. - Attributes: uri (str): Required. The HTTP or HTTPS scheme URI. """ - uri = proto.Field(proto.STRING, number=1) - - title = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) + title = proto.Field(proto.STRING, number=1,) open_uri_action = proto.Field( proto.MESSAGE, number=2, message="Intent.Message.BasicCard.Button.OpenUriAction", ) - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - - formatted_text = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) + formatted_text = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.BasicCard.Button", ) @@ -599,11 +557,10 @@ class Suggestion(proto.Message): suggestion chip. """ - title = proto.Field(proto.STRING, number=1) + title = proto.Field(proto.STRING, number=1,) class Suggestions(proto.Message): r"""The collection of suggestions. - Attributes: suggestions (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.Suggestion]): Required. The list of suggested replies. @@ -626,13 +583,11 @@ class LinkOutSuggestion(proto.Message): when the user taps the suggestion chip. """ - destination_name = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) + destination_name = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) class ListSelect(proto.Message): r"""The card for presenting a list of options to select from. - Attributes: title (str): Optional. The overall title of the list. @@ -644,7 +599,6 @@ class ListSelect(proto.Message): class Item(proto.Message): r"""An item in the list. - Attributes: info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): Required. Additional information about this @@ -660,26 +614,20 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - title = proto.Field(proto.STRING, number=1) - + title = proto.Field(proto.STRING, number=1,) items = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.ListSelect.Item", ) - - subtitle = proto.Field(proto.STRING, number=3) + subtitle = proto.Field(proto.STRING, number=3,) class CarouselSelect(proto.Message): r"""The card for presenting a carousel of options to select from. - Attributes: items (Sequence[google.cloud.dialogflow_v2beta1.types.Intent.Message.CarouselSelect.Item]): Required. Carousel items. @@ -687,7 +635,6 @@ class CarouselSelect(proto.Message): class Item(proto.Message): r"""An item in the carousel. - Attributes: info (google.cloud.dialogflow_v2beta1.types.Intent.Message.SelectItemInfo): Required. Additional info about the option @@ -703,11 +650,8 @@ class Item(proto.Message): info = proto.Field( proto.MESSAGE, number=1, message="Intent.Message.SelectItemInfo", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) @@ -729,13 +673,11 @@ class SelectItemInfo(proto.Message): used to trigger this item in dialog. """ - key = proto.Field(proto.STRING, number=1) - - synonyms = proto.RepeatedField(proto.STRING, number=2) + key = proto.Field(proto.STRING, number=1,) + synonyms = proto.RepeatedField(proto.STRING, number=2,) class TelephonyPlayAudio(proto.Message): r"""Plays audio from a file in Telephony Gateway. - Attributes: audio_uri (str): Required. URI to a Google Cloud Storage object containing @@ -755,7 +697,7 @@ class TelephonyPlayAudio(proto.Message): ``TelephonySynthesizeSpeech`` message with SSML. """ - audio_uri = proto.Field(proto.STRING, number=1) + audio_uri = proto.Field(proto.STRING, number=1,) class TelephonySynthesizeSpeech(proto.Message): r"""Synthesizes speech and plays back the synthesized audio to the @@ -774,13 +716,11 @@ class TelephonySynthesizeSpeech(proto.Message): `SSML `__. """ - text = proto.Field(proto.STRING, number=1, oneof="source") - - ssml = proto.Field(proto.STRING, number=2, oneof="source") + text = proto.Field(proto.STRING, number=1, oneof="source",) + ssml = proto.Field(proto.STRING, number=2, oneof="source",) class TelephonyTransferCall(proto.Message): r"""Transfers the call in Telephony Gateway. - Attributes: phone_number (str): Required. The phone number to transfer the call to in `E.164 @@ -790,11 +730,10 @@ class TelephonyTransferCall(proto.Message): (+1xxxyyyzzzz). """ - phone_number = proto.Field(proto.STRING, number=1) + phone_number = proto.Field(proto.STRING, number=1,) class RbmText(proto.Message): r"""Rich Business Messaging (RBM) text response with suggestions. - Attributes: text (str): Required. Text sent and displayed to the @@ -804,8 +743,7 @@ class RbmText(proto.Message): the user. """ - text = proto.Field(proto.STRING, number=1) - + text = proto.Field(proto.STRING, number=1,) rbm_suggestion = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.RbmSuggestion", ) @@ -840,7 +778,6 @@ class CardWidth(proto.Enum): card_width = proto.Field( proto.ENUM, number=1, enum="Intent.Message.RbmCarouselCard.CardWidth", ) - card_contents = proto.RepeatedField( proto.MESSAGE, number=2, message="Intent.Message.RbmCardContent", ) @@ -885,20 +822,17 @@ class ThumbnailImageAlignment(proto.Enum): number=1, enum="Intent.Message.RbmStandaloneCard.CardOrientation", ) - thumbnail_image_alignment = proto.Field( proto.ENUM, number=2, enum="Intent.Message.RbmStandaloneCard.ThumbnailImageAlignment", ) - card_content = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.RbmCardContent", ) class RbmCardContent(proto.Message): r"""Rich Business Messaging (RBM) Card content - Attributes: title (str): Optional. Title of the card (at most 200 @@ -970,26 +904,21 @@ class Height(proto.Enum): MEDIUM = 2 TALL = 3 - file_uri = proto.Field(proto.STRING, number=1) - - thumbnail_uri = proto.Field(proto.STRING, number=2) - + file_uri = proto.Field(proto.STRING, number=1,) + thumbnail_uri = proto.Field(proto.STRING, number=2,) height = proto.Field( proto.ENUM, number=3, enum="Intent.Message.RbmCardContent.RbmMedia.Height", ) - title = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) media = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.RbmCardContent.RbmMedia", ) - suggestions = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.RbmSuggestion", ) @@ -1014,7 +943,6 @@ class RbmSuggestion(proto.Message): oneof="suggestion", message="Intent.Message.RbmSuggestedReply", ) - action = proto.Field( proto.MESSAGE, number=2, @@ -1037,9 +965,8 @@ class RbmSuggestedReply(proto.Message): logic. """ - text = proto.Field(proto.STRING, number=1) - - postback_data = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + postback_data = proto.Field(proto.STRING, number=2,) class RbmSuggestedAction(proto.Message): r"""Rich Business Messaging (RBM) suggested client-side action @@ -1077,7 +1004,7 @@ class RbmSuggestedActionDial(proto.Message): example of a correctly formatted phone number: +15556767888. """ - phone_number = proto.Field(proto.STRING, number=1) + phone_number = proto.Field(proto.STRING, number=1,) class RbmSuggestedActionOpenUri(proto.Message): r"""Opens the user's default web browser app to the specified uri @@ -1091,31 +1018,27 @@ class RbmSuggestedActionOpenUri(proto.Message): Required. The uri to open on the user device """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class RbmSuggestedActionShareLocation(proto.Message): r"""Opens the device's location chooser so the user can pick a location to send back to the agent. - """ - - text = proto.Field(proto.STRING, number=1) - - postback_data = proto.Field(proto.STRING, number=2) + """ + text = proto.Field(proto.STRING, number=1,) + postback_data = proto.Field(proto.STRING, number=2,) dial = proto.Field( proto.MESSAGE, number=3, oneof="action", message="Intent.Message.RbmSuggestedAction.RbmSuggestedActionDial", ) - open_url = proto.Field( proto.MESSAGE, number=4, oneof="action", message="Intent.Message.RbmSuggestedAction.RbmSuggestedActionOpenUri", ) - share_location = proto.Field( proto.MESSAGE, number=5, @@ -1125,7 +1048,6 @@ class RbmSuggestedActionShareLocation(proto.Message): class MediaContent(proto.Message): r"""The media content card for Actions on Google. - Attributes: media_type (google.cloud.dialogflow_v2beta1.types.Intent.Message.MediaContent.ResponseMediaType): Optional. What type of media is the content @@ -1141,7 +1063,6 @@ class ResponseMediaType(proto.Enum): class ResponseMediaObject(proto.Message): r"""Response media object for media content card. - Attributes: name (str): Required. Name of media card. @@ -1157,32 +1078,27 @@ class ResponseMediaObject(proto.Message): Required. Url where the media is stored. """ - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) large_image = proto.Field( proto.MESSAGE, number=3, oneof="image", message="Intent.Message.Image", ) - icon = proto.Field( proto.MESSAGE, number=4, oneof="image", message="Intent.Message.Image", ) - - content_url = proto.Field(proto.STRING, number=5) + content_url = proto.Field(proto.STRING, number=5,) media_type = proto.Field( proto.ENUM, number=1, enum="Intent.Message.MediaContent.ResponseMediaType", ) - media_objects = proto.RepeatedField( proto.MESSAGE, number=2, @@ -1217,7 +1133,6 @@ class ImageDisplayOptions(proto.Enum): class BrowseCarouselCardItem(proto.Message): r"""Browsing carousel tile - Attributes: open_uri_action (google.cloud.dialogflow_v2beta1.types.Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction): Required. Action to present to the user. @@ -1237,7 +1152,6 @@ class BrowseCarouselCardItem(proto.Message): class OpenUrlAction(proto.Message): r"""Actions on Google action to open a given url. - Attributes: url (str): Required. URL @@ -1253,8 +1167,7 @@ class UrlTypeHint(proto.Enum): AMP_ACTION = 1 AMP_CONTENT = 2 - url = proto.Field(proto.STRING, number=1) - + url = proto.Field(proto.STRING, number=1,) url_type_hint = proto.Field( proto.ENUM, number=3, @@ -1266,23 +1179,18 @@ class UrlTypeHint(proto.Enum): number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem.OpenUrlAction", ) - - title = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + title = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) image = proto.Field( proto.MESSAGE, number=4, message="Intent.Message.Image", ) - - footer = proto.Field(proto.STRING, number=5) + footer = proto.Field(proto.STRING, number=5,) items = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.BrowseCarouselCard.BrowseCarouselCardItem", ) - image_display_options = proto.Field( proto.ENUM, number=2, @@ -1291,7 +1199,6 @@ class UrlTypeHint(proto.Enum): class TableCard(proto.Message): r"""Table card for Actions on Google. - Attributes: title (str): Required. Title of the card. @@ -1309,22 +1216,17 @@ class TableCard(proto.Message): Optional. List of buttons for the card. """ - title = proto.Field(proto.STRING, number=1) - - subtitle = proto.Field(proto.STRING, number=2) - + title = proto.Field(proto.STRING, number=1,) + subtitle = proto.Field(proto.STRING, number=2,) image = proto.Field( proto.MESSAGE, number=3, message="Intent.Message.Image", ) - column_properties = proto.RepeatedField( proto.MESSAGE, number=4, message="Intent.Message.ColumnProperties", ) - rows = proto.RepeatedField( proto.MESSAGE, number=5, message="Intent.Message.TableCardRow", ) - buttons = proto.RepeatedField( proto.MESSAGE, number=6, message="Intent.Message.BasicCard.Button", ) @@ -1348,8 +1250,7 @@ class HorizontalAlignment(proto.Enum): CENTER = 2 TRAILING = 3 - header = proto.Field(proto.STRING, number=1) - + header = proto.Field(proto.STRING, number=1,) horizontal_alignment = proto.Field( proto.ENUM, number=2, @@ -1372,8 +1273,7 @@ class TableCardRow(proto.Message): cells = proto.RepeatedField( proto.MESSAGE, number=1, message="Intent.Message.TableCardCell", ) - - divider_after = proto.Field(proto.BOOL, number=2) + divider_after = proto.Field(proto.BOOL, number=2,) class TableCardCell(proto.Message): r"""Cell of @@ -1384,138 +1284,117 @@ class TableCardCell(proto.Message): Required. Text in this cell. """ - text = proto.Field(proto.STRING, number=1) + text = proto.Field(proto.STRING, number=1,) text = proto.Field( proto.MESSAGE, number=1, oneof="message", message="Intent.Message.Text", ) - image = proto.Field( proto.MESSAGE, number=2, oneof="message", message="Intent.Message.Image", ) - quick_replies = proto.Field( proto.MESSAGE, number=3, oneof="message", message="Intent.Message.QuickReplies", ) - card = proto.Field( proto.MESSAGE, number=4, oneof="message", message="Intent.Message.Card", ) - payload = proto.Field( - proto.MESSAGE, number=5, oneof="message", message=struct.Struct, + proto.MESSAGE, number=5, oneof="message", message=struct_pb2.Struct, ) - simple_responses = proto.Field( proto.MESSAGE, number=7, oneof="message", message="Intent.Message.SimpleResponses", ) - basic_card = proto.Field( proto.MESSAGE, number=8, oneof="message", message="Intent.Message.BasicCard", ) - suggestions = proto.Field( proto.MESSAGE, number=9, oneof="message", message="Intent.Message.Suggestions", ) - link_out_suggestion = proto.Field( proto.MESSAGE, number=10, oneof="message", message="Intent.Message.LinkOutSuggestion", ) - list_select = proto.Field( proto.MESSAGE, number=11, oneof="message", message="Intent.Message.ListSelect", ) - carousel_select = proto.Field( proto.MESSAGE, number=12, oneof="message", message="Intent.Message.CarouselSelect", ) - telephony_play_audio = proto.Field( proto.MESSAGE, number=13, oneof="message", message="Intent.Message.TelephonyPlayAudio", ) - telephony_synthesize_speech = proto.Field( proto.MESSAGE, number=14, oneof="message", message="Intent.Message.TelephonySynthesizeSpeech", ) - telephony_transfer_call = proto.Field( proto.MESSAGE, number=15, oneof="message", message="Intent.Message.TelephonyTransferCall", ) - rbm_text = proto.Field( proto.MESSAGE, number=18, oneof="message", message="Intent.Message.RbmText", ) - rbm_standalone_rich_card = proto.Field( proto.MESSAGE, number=19, oneof="message", message="Intent.Message.RbmStandaloneCard", ) - rbm_carousel_rich_card = proto.Field( proto.MESSAGE, number=20, oneof="message", message="Intent.Message.RbmCarouselCard", ) - browse_carousel_card = proto.Field( proto.MESSAGE, number=22, oneof="message", message="Intent.Message.BrowseCarouselCard", ) - table_card = proto.Field( proto.MESSAGE, number=23, oneof="message", message="Intent.Message.TableCard", ) - media_content = proto.Field( proto.MESSAGE, number=24, oneof="message", message="Intent.Message.MediaContent", ) - platform = proto.Field(proto.ENUM, number=6, enum="Intent.Message.Platform",) class FollowupIntentInfo(proto.Message): r"""Represents a single followup intent in the chain. - Attributes: followup_intent_name (str): The unique identifier of the followup intent. Format: @@ -1525,56 +1404,35 @@ class FollowupIntentInfo(proto.Message): Format: ``projects//agent/intents/``. """ - followup_intent_name = proto.Field(proto.STRING, number=1) - - parent_followup_intent_name = proto.Field(proto.STRING, number=2) - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) + followup_intent_name = proto.Field(proto.STRING, number=1,) + parent_followup_intent_name = proto.Field(proto.STRING, number=2,) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) webhook_state = proto.Field(proto.ENUM, number=6, enum=WebhookState,) - - priority = proto.Field(proto.INT32, number=3) - - is_fallback = proto.Field(proto.BOOL, number=4) - - ml_enabled = proto.Field(proto.BOOL, number=5) - - ml_disabled = proto.Field(proto.BOOL, number=19) - - live_agent_handoff = proto.Field(proto.BOOL, number=20) - - end_interaction = proto.Field(proto.BOOL, number=21) - - input_context_names = proto.RepeatedField(proto.STRING, number=7) - - events = proto.RepeatedField(proto.STRING, number=8) - + priority = proto.Field(proto.INT32, number=3,) + is_fallback = proto.Field(proto.BOOL, number=4,) + ml_enabled = proto.Field(proto.BOOL, number=5,) + ml_disabled = proto.Field(proto.BOOL, number=19,) + live_agent_handoff = proto.Field(proto.BOOL, number=20,) + end_interaction = proto.Field(proto.BOOL, number=21,) + input_context_names = proto.RepeatedField(proto.STRING, number=7,) + events = proto.RepeatedField(proto.STRING, number=8,) training_phrases = proto.RepeatedField( proto.MESSAGE, number=9, message=TrainingPhrase, ) - - action = proto.Field(proto.STRING, number=10) - + action = proto.Field(proto.STRING, number=10,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=11, message=context.Context, ) - - reset_contexts = proto.Field(proto.BOOL, number=12) - + reset_contexts = proto.Field(proto.BOOL, number=12,) parameters = proto.RepeatedField(proto.MESSAGE, number=13, message=Parameter,) - messages = proto.RepeatedField(proto.MESSAGE, number=14, message=Message,) - default_response_platforms = proto.RepeatedField( proto.ENUM, number=15, enum=Message.Platform, ) - - root_followup_intent_name = proto.Field(proto.STRING, number=16) - - parent_followup_intent_name = proto.Field(proto.STRING, number=17) - + root_followup_intent_name = proto.Field(proto.STRING, number=16,) + parent_followup_intent_name = proto.Field(proto.STRING, number=17,) followup_intent_info = proto.RepeatedField( proto.MESSAGE, number=18, message=FollowupIntentInfo, ) @@ -1606,15 +1464,11 @@ class ListIntentsRequest(proto.Message): list 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=3, enum="IntentView",) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) class ListIntentsResponse(proto.Message): @@ -1636,8 +1490,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): @@ -1661,10 +1514,8 @@ class GetIntentRequest(proto.Message): returned intent. """ - 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,) intent_view = proto.Field(proto.ENUM, number=3, enum="IntentView",) @@ -1692,12 +1543,9 @@ class CreateIntentRequest(proto.Message): returned intent. """ - 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,) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1723,11 +1571,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, + ) intent_view = proto.Field(proto.ENUM, number=4, enum="IntentView",) @@ -1747,7 +1594,7 @@ class DeleteIntentRequest(proto.Message): - ``projects//locations//agent/intents/`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class BatchUpdateIntentsRequest(proto.Message): @@ -1784,18 +1631,15 @@ class BatchUpdateIntentsRequest(proto.Message): returned intent. """ - parent = proto.Field(proto.STRING, number=1) - - intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch") - + parent = proto.Field(proto.STRING, number=1,) + intent_batch_uri = proto.Field(proto.STRING, number=2, oneof="intent_batch",) intent_batch_inline = proto.Field( proto.MESSAGE, number=3, oneof="intent_batch", message="IntentBatch", ) - - language_code = proto.Field(proto.STRING, number=4) - - update_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask.FieldMask,) - + language_code = proto.Field(proto.STRING, number=4,) + update_mask = proto.Field( + proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask, + ) intent_view = proto.Field(proto.ENUM, number=6, enum="IntentView",) @@ -1827,14 +1671,12 @@ class BatchDeleteIntentsRequest(proto.Message): ``name`` must be filled in. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) intents = proto.RepeatedField(proto.MESSAGE, number=2, message="Intent",) class IntentBatch(proto.Message): r"""This message is a wrapper around a collection of intents. - Attributes: intents (Sequence[google.cloud.dialogflow_v2beta1.types.Intent]): A collection of intents. diff --git a/google/cloud/dialogflow_v2beta1/types/knowledge_base.py b/google/cloud/dialogflow_v2beta1/types/knowledge_base.py index aac1458c9..bc167796b 100644 --- a/google/cloud/dialogflow_v2beta1/types/knowledge_base.py +++ b/google/cloud/dialogflow_v2beta1/types/knowledge_base.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( @@ -64,11 +61,9 @@ class KnowledgeBase(proto.Message): populated, the default language en-us applies. """ - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + display_name = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=4,) class ListKnowledgeBasesRequest(proto.Message): @@ -116,13 +111,10 @@ class ListKnowledgeBasesRequest(proto.Message): Filtering `__. """ - 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 ListKnowledgeBasesResponse(proto.Message): @@ -145,8 +137,7 @@ def raw_page(self): knowledge_bases = proto.RepeatedField( proto.MESSAGE, number=1, message="KnowledgeBase", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetKnowledgeBaseRequest(proto.Message): @@ -159,7 +150,7 @@ class GetKnowledgeBaseRequest(proto.Message): ``projects//locations//knowledgeBases/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateKnowledgeBaseRequest(proto.Message): @@ -174,8 +165,7 @@ class CreateKnowledgeBaseRequest(proto.Message): Required. The knowledge base to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) knowledge_base = proto.Field(proto.MESSAGE, number=2, message="KnowledgeBase",) @@ -193,9 +183,8 @@ class DeleteKnowledgeBaseRequest(proto.Message): base are also deleted. """ - 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 UpdateKnowledgeBaseRequest(proto.Message): @@ -212,8 +201,9 @@ class UpdateKnowledgeBaseRequest(proto.Message): """ knowledge_base = proto.Field(proto.MESSAGE, number=1, message="KnowledgeBase",) - - 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, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/participant.py b/google/cloud/dialogflow_v2beta1/types/participant.py index 1cc49a74a..b38c7e8a9 100644 --- a/google/cloud/dialogflow_v2beta1/types/participant.py +++ b/google/cloud/dialogflow_v2beta1/types/participant.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import session -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 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( @@ -123,16 +120,13 @@ class Role(proto.Enum): AUTOMATED_AGENT = 2 END_USER = 3 - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) role = proto.Field(proto.ENUM, number=2, enum=Role,) - - obfuscated_external_user_id = proto.Field(proto.STRING, number=7) + obfuscated_external_user_id = proto.Field(proto.STRING, number=7,) class Message(proto.Message): r"""Represents a message posted into a conversation. - Attributes: name (str): Optional. The unique identifier of the message. Format: @@ -160,24 +154,16 @@ class Message(proto.Message): for the message. """ - name = proto.Field(proto.STRING, number=1) - - content = proto.Field(proto.STRING, number=2) - - language_code = proto.Field(proto.STRING, number=3) - - participant = proto.Field(proto.STRING, number=4) - + name = proto.Field(proto.STRING, number=1,) + content = proto.Field(proto.STRING, number=2,) + language_code = proto.Field(proto.STRING, number=3,) + participant = proto.Field(proto.STRING, number=4,) participant_role = proto.Field(proto.ENUM, number=5, enum="Participant.Role",) - - create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) - - send_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - + create_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) + send_time = proto.Field(proto.MESSAGE, number=9, message=timestamp_pb2.Timestamp,) message_annotation = proto.Field( proto.MESSAGE, number=7, message="MessageAnnotation", ) - sentiment_analysis = proto.Field( proto.MESSAGE, number=8, message=session.SentimentAnalysisResult, ) @@ -196,8 +182,7 @@ class CreateParticipantRequest(proto.Message): Required. The participant to create. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) participant = proto.Field(proto.MESSAGE, number=2, message="Participant",) @@ -211,7 +196,7 @@ class GetParticipantRequest(proto.Message): ``projects//locations//conversations//participants/``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListParticipantsRequest(proto.Message): @@ -232,11 +217,9 @@ class ListParticipantsRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListParticipantsResponse(proto.Message): @@ -257,8 +240,7 @@ def raw_page(self): return self participants = proto.RepeatedField(proto.MESSAGE, number=1, message="Participant",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class UpdateParticipantRequest(proto.Message): @@ -274,8 +256,9 @@ class UpdateParticipantRequest(proto.Message): """ participant = proto.Field(proto.MESSAGE, number=1, message="Participant",) - - 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 OutputAudio(proto.Message): @@ -293,13 +276,11 @@ class OutputAudio(proto.Message): config = proto.Field( proto.MESSAGE, number=1, message=audio_config.OutputAudioConfig, ) - - audio = proto.Field(proto.BYTES, number=2) + audio = proto.Field(proto.BYTES, number=2,) class AutomatedAgentReply(proto.Message): r"""Represents a response from an automated agent. - Attributes: detect_intent_response (google.cloud.dialogflow_v2beta1.types.DetectIntentResponse): Response of the Dialogflow @@ -324,16 +305,14 @@ class AutomatedAgentReply(proto.Message): detect_intent_response = proto.Field( proto.MESSAGE, number=1, oneof="response", message=session.DetectIntentResponse, ) - response_messages = proto.RepeatedField( proto.MESSAGE, number=3, message="ResponseMessage", ) - - intent = proto.Field(proto.STRING, number=4, oneof="match") - - event = proto.Field(proto.STRING, number=5, oneof="match") - - cx_session_parameters = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) + intent = proto.Field(proto.STRING, number=4, oneof="match",) + event = proto.Field(proto.STRING, number=5, oneof="match",) + cx_session_parameters = proto.Field( + proto.MESSAGE, number=6, message=struct_pb2.Struct, + ) class SuggestionFeature(proto.Message): @@ -404,29 +383,23 @@ class AnalyzeContentRequest(proto.Message): only idempotent if a ``request_id`` is provided. """ - participant = proto.Field(proto.STRING, number=1) - + participant = proto.Field(proto.STRING, number=1,) text_input = proto.Field( proto.MESSAGE, number=6, oneof="input", message=session.TextInput, ) - event_input = proto.Field( proto.MESSAGE, number=8, oneof="input", message=session.EventInput, ) - reply_audio_config = proto.Field( proto.MESSAGE, number=5, message=audio_config.OutputAudioConfig, ) - query_params = proto.Field( proto.MESSAGE, number=9, message=session.QueryParameters, ) - message_send_time = proto.Field( - proto.MESSAGE, number=10, message=timestamp.Timestamp, + proto.MESSAGE, number=10, message=timestamp_pb2.Timestamp, ) - - request_id = proto.Field(proto.STRING, number=11) + request_id = proto.Field(proto.STRING, number=11,) class DtmfParameters(proto.Message): @@ -439,7 +412,7 @@ class DtmfParameters(proto.Message): in the next request. """ - accepts_dtmf_input = proto.Field(proto.BOOL, number=1) + accepts_dtmf_input = proto.Field(proto.BOOL, number=1,) class AnalyzeContentResponse(proto.Message): @@ -489,24 +462,18 @@ class AnalyzeContentResponse(proto.Message): Indicates the parameters of DTMF. """ - reply_text = proto.Field(proto.STRING, number=1) - + reply_text = proto.Field(proto.STRING, number=1,) reply_audio = proto.Field(proto.MESSAGE, number=2, message="OutputAudio",) - automated_agent_reply = proto.Field( proto.MESSAGE, number=3, message="AutomatedAgentReply", ) - message = proto.Field(proto.MESSAGE, number=5, message="Message",) - human_agent_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=6, message="SuggestionResult", ) - end_user_suggestion_results = proto.RepeatedField( proto.MESSAGE, number=7, message="SuggestionResult", ) - dtmf_parameters = proto.Field(proto.MESSAGE, number=9, message="DtmfParameters",) @@ -540,16 +507,13 @@ class AnnotatedMessagePart(proto.Message): """ - text = proto.Field(proto.STRING, number=1) - - entity_type = proto.Field(proto.STRING, number=2) - - formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct.Value,) + text = proto.Field(proto.STRING, number=1,) + entity_type = proto.Field(proto.STRING, number=2,) + formatted_value = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Value,) class MessageAnnotation(proto.Message): r"""Represents the result of annotation for the message. - Attributes: parts (Sequence[google.cloud.dialogflow_v2beta1.types.AnnotatedMessagePart]): Optional. The collection of annotated message parts ordered @@ -564,13 +528,11 @@ class MessageAnnotation(proto.Message): parts = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotatedMessagePart", ) - - contain_entities = proto.Field(proto.BOOL, number=2) + contain_entities = proto.Field(proto.BOOL, number=2,) class ArticleAnswer(proto.Message): r"""Represents article answer. - Attributes: title (str): The article title. @@ -587,20 +549,15 @@ class ArticleAnswer(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents answer from "frequently asked questions". - Attributes: answer (str): The piece of text from the ``source`` knowledge base @@ -625,22 +582,16 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class SmartReplyAnswer(proto.Message): r"""Represents a smart reply answer. - Attributes: reply (str): The content of the reply. @@ -656,11 +607,9 @@ class SmartReplyAnswer(proto.Message): ID>/answerRecords/". """ - reply = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - answer_record = proto.Field(proto.STRING, number=3) + reply = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + answer_record = proto.Field(proto.STRING, number=3,) class SuggestionResult(proto.Message): @@ -685,23 +634,20 @@ class SuggestionResult(proto.Message): """ error = proto.Field( - proto.MESSAGE, number=1, oneof="suggestion_response", message=status.Status, + proto.MESSAGE, number=1, oneof="suggestion_response", message=status_pb2.Status, ) - suggest_articles_response = proto.Field( proto.MESSAGE, number=2, oneof="suggestion_response", message="SuggestArticlesResponse", ) - suggest_faq_answers_response = proto.Field( proto.MESSAGE, number=3, oneof="suggestion_response", message="SuggestFaqAnswersResponse", ) - suggest_smart_replies_response = proto.Field( proto.MESSAGE, number=4, @@ -733,11 +679,9 @@ class SuggestArticlesRequest(proto.Message): 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestArticlesResponse(proto.Message): @@ -766,10 +710,8 @@ class SuggestArticlesResponse(proto.Message): article_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="ArticleAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersRequest(proto.Message): @@ -794,11 +736,9 @@ class SuggestFaqAnswersRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestFaqAnswersResponse(proto.Message): @@ -825,10 +765,8 @@ class SuggestFaqAnswersResponse(proto.Message): """ faq_answers = proto.RepeatedField(proto.MESSAGE, number=1, message="FaqAnswer",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestSmartRepliesRequest(proto.Message): @@ -859,15 +797,12 @@ class SuggestSmartRepliesRequest(proto.Message): suggestion. By default 20 and at most 50. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) current_text_input = proto.Field( proto.MESSAGE, number=4, message=session.TextInput, ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class SuggestSmartRepliesResponse(proto.Message): @@ -899,15 +834,12 @@ class SuggestSmartRepliesResponse(proto.Message): smart_reply_answers = proto.RepeatedField( proto.MESSAGE, number=1, message="SmartReplyAnswer", ) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class Suggestion(proto.Message): r"""Represents a suggestion for a human agent. - Attributes: name (str): Output only. The name of this suggestion. Format: @@ -931,7 +863,6 @@ class Suggestion(proto.Message): class Article(proto.Message): r"""Represents suggested article. - Attributes: title (str): Output only. The article title. @@ -950,15 +881,11 @@ class Article(proto.Message): ID>/answerRecords/". """ - title = proto.Field(proto.STRING, number=1) - - uri = proto.Field(proto.STRING, number=2) - - snippets = proto.RepeatedField(proto.STRING, number=3) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) + title = proto.Field(proto.STRING, number=1,) + uri = proto.Field(proto.STRING, number=2,) + snippets = proto.RepeatedField(proto.STRING, number=3,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) class FaqAnswer(proto.Message): r"""Represents suggested answer from "frequently asked @@ -990,27 +917,18 @@ class FaqAnswer(proto.Message): ID>/answerRecords/". """ - answer = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) - - question = proto.Field(proto.STRING, number=3) - - source = proto.Field(proto.STRING, number=4) - - metadata = proto.MapField(proto.STRING, proto.STRING, number=5) - - answer_record = proto.Field(proto.STRING, number=6) - - name = proto.Field(proto.STRING, number=1) + answer = proto.Field(proto.STRING, number=1,) + confidence = proto.Field(proto.FLOAT, number=2,) + question = proto.Field(proto.STRING, number=3,) + source = proto.Field(proto.STRING, number=4,) + metadata = proto.MapField(proto.STRING, proto.STRING, number=5,) + answer_record = proto.Field(proto.STRING, number=6,) + name = proto.Field(proto.STRING, number=1,) articles = proto.RepeatedField(proto.MESSAGE, number=2, message=Article,) - faq_answers = proto.RepeatedField(proto.MESSAGE, number=4, message=FaqAnswer,) - - create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - latest_message = proto.Field(proto.STRING, number=7) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + latest_message = proto.Field(proto.STRING, number=7,) class ListSuggestionsRequest(proto.Message): @@ -1035,19 +953,16 @@ class ListSuggestionsRequest(proto.Message): are supported. ``create_time`` only support milliseconds accuracy. E.g., ``create_time_epoch_microseconds > 1551790877964485`` or - ``create_time > 2017-01-15T01:30:15.01Z`` + ``create_time > "2017-01-15T01:30:15.01Z"`` For more information about filtering, see `API Filtering `__. """ - 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 ListSuggestionsResponse(proto.Message): @@ -1071,8 +986,7 @@ def raw_page(self): return self suggestions = proto.RepeatedField(proto.MESSAGE, number=1, message="Suggestion",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CompileSuggestionRequest(proto.Message): @@ -1097,11 +1011,9 @@ class CompileSuggestionRequest(proto.Message): suggestion. If zero or less than zero, 20 is used. """ - parent = proto.Field(proto.STRING, number=1) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + parent = proto.Field(proto.STRING, number=1,) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class CompileSuggestionResponse(proto.Message): @@ -1127,15 +1039,12 @@ class CompileSuggestionResponse(proto.Message): """ suggestion = proto.Field(proto.MESSAGE, number=1, message="Suggestion",) - - latest_message = proto.Field(proto.STRING, number=2) - - context_size = proto.Field(proto.INT32, number=3) + latest_message = proto.Field(proto.STRING, number=2,) + context_size = proto.Field(proto.INT32, number=3,) class ResponseMessage(proto.Message): r"""Response messages from an automated agent. - Attributes: text (google.cloud.dialogflow_v2beta1.types.ResponseMessage.Text): Returns a text response. @@ -1151,13 +1060,12 @@ class ResponseMessage(proto.Message): class Text(proto.Message): r"""The text response message. - Attributes: text (Sequence[str]): A collection of text responses. """ - text = proto.RepeatedField(proto.STRING, number=1) + text = proto.RepeatedField(proto.STRING, number=1,) class LiveAgentHandoff(proto.Message): r"""Indicates that the conversation should be handed off to a human @@ -1180,23 +1088,20 @@ 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 EndInteraction(proto.Message): r"""Indicates that interaction with the Dialogflow agent has ended. - """ + """ 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, ) - live_agent_handoff = proto.Field( proto.MESSAGE, number=3, oneof="message", message=LiveAgentHandoff, ) - end_interaction = proto.Field( proto.MESSAGE, number=4, oneof="message", message=EndInteraction, ) diff --git a/google/cloud/dialogflow_v2beta1/types/session.py b/google/cloud/dialogflow_v2beta1/types/session.py index 83f336c1d..6423b5774 100644 --- a/google/cloud/dialogflow_v2beta1/types/session.py +++ b/google/cloud/dialogflow_v2beta1/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,20 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config as gcd_audio_config from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent from google.cloud.dialogflow_v2beta1.types import session_entity_type -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.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 field_mask_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( @@ -53,7 +50,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. @@ -113,26 +109,20 @@ class DetectIntentRequest(proto.Message): minute of speech audio data. """ - 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=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=5) + input_audio = proto.Field(proto.BYTES, number=5,) class DetectIntentResponse(proto.Message): r"""The message returned from the DetectIntent method. - Attributes: response_id (str): The unique identifier of the response. It can @@ -171,18 +161,13 @@ 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",) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=5, message="QueryResult", ) - - webhook_status = proto.Field(proto.MESSAGE, number=3, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=4) - + webhook_status = proto.Field(proto.MESSAGE, number=3, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -190,7 +175,6 @@ class DetectIntentResponse(proto.Message): class QueryParameters(proto.Message): r"""Represents the parameters of the conversational query. - Attributes: time_zone (str): The time zone of this conversational query from the `time @@ -251,29 +235,20 @@ 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,) contexts = proto.RepeatedField(proto.MESSAGE, number=3, message=context.Context,) - - reset_contexts = proto.Field(proto.BOOL, number=4) - + reset_contexts = proto.Field(proto.BOOL, number=4,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=5, message=session_entity_type.SessionEntityType, ) - - payload = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - - knowledge_base_names = proto.RepeatedField(proto.STRING, number=12) - + payload = proto.Field(proto.MESSAGE, number=6, message=struct_pb2.Struct,) + knowledge_base_names = proto.RepeatedField(proto.STRING, number=12,) sentiment_analysis_request_config = proto.Field( proto.MESSAGE, number=10, message="SentimentAnalysisRequestConfig", ) - sub_agents = proto.RepeatedField(proto.MESSAGE, number=13, message=agent.SubAgent,) - - webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14) + webhook_headers = proto.MapField(proto.STRING, proto.STRING, number=14,) class QueryInput(proto.Message): @@ -304,11 +279,8 @@ class QueryInput(proto.Message): oneof="input", message=gcd_audio_config.InputAudioConfig, ) - text = proto.Field(proto.MESSAGE, number=2, oneof="input", message="TextInput",) - event = proto.Field(proto.MESSAGE, number=3, oneof="input", message="EventInput",) - dtmf = proto.Field( proto.MESSAGE, number=4, @@ -436,42 +408,27 @@ class QueryResult(proto.Message): decreasing ``KnowledgeAnswers.match_confidence``. """ - query_text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=15) - - speech_recognition_confidence = proto.Field(proto.FLOAT, number=2) - - action = proto.Field(proto.STRING, number=3) - - parameters = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - - all_required_params_present = proto.Field(proto.BOOL, number=5) - - fulfillment_text = proto.Field(proto.STRING, number=6) - + query_text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=15,) + speech_recognition_confidence = proto.Field(proto.FLOAT, number=2,) + action = proto.Field(proto.STRING, number=3,) + parameters = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) + all_required_params_present = proto.Field(proto.BOOL, number=5,) + fulfillment_text = proto.Field(proto.STRING, number=6,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=7, message=gcd_intent.Intent.Message, ) - - webhook_source = proto.Field(proto.STRING, number=8) - - webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) - + webhook_source = proto.Field(proto.STRING, number=8,) + webhook_payload = proto.Field(proto.MESSAGE, number=9, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=10, message=context.Context, ) - intent = proto.Field(proto.MESSAGE, number=11, message=gcd_intent.Intent,) - - intent_detection_confidence = proto.Field(proto.FLOAT, number=12) - - diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct.Struct,) - + intent_detection_confidence = proto.Field(proto.FLOAT, number=12,) + diagnostic_info = proto.Field(proto.MESSAGE, number=14, message=struct_pb2.Struct,) sentiment_analysis_result = proto.Field( proto.MESSAGE, number=17, message="SentimentAnalysisResult", ) - knowledge_answers = proto.Field( proto.MESSAGE, number=18, message="KnowledgeAnswers", ) @@ -479,7 +436,6 @@ class QueryResult(proto.Message): class KnowledgeAnswers(proto.Message): r"""Represents the result of querying a Knowledge base. - Attributes: answers (Sequence[google.cloud.dialogflow_v2beta1.types.KnowledgeAnswers.Answer]): A list of answers from Knowledge Connector. @@ -487,7 +443,6 @@ class KnowledgeAnswers(proto.Message): class Answer(proto.Message): r"""An answer from Knowledge Connector. - Attributes: source (str): Indicates which Knowledge Document this answer was extracted @@ -528,17 +483,13 @@ class MatchConfidenceLevel(proto.Enum): MEDIUM = 2 HIGH = 3 - source = proto.Field(proto.STRING, number=1) - - faq_question = proto.Field(proto.STRING, number=2) - - answer = proto.Field(proto.STRING, number=3) - + source = proto.Field(proto.STRING, number=1,) + faq_question = proto.Field(proto.STRING, number=2,) + answer = proto.Field(proto.STRING, number=3,) match_confidence_level = proto.Field( proto.ENUM, number=4, enum="KnowledgeAnswers.Answer.MatchConfidenceLevel", ) - - match_confidence = proto.Field(proto.FLOAT, number=5) + match_confidence = proto.Field(proto.FLOAT, number=5,) answers = proto.RepeatedField(proto.MESSAGE, number=1, message=Answer,) @@ -653,23 +604,17 @@ class StreamingDetectIntentRequest(proto.Message): exceed 1 minute. """ - 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",) - - single_utterance = proto.Field(proto.BOOL, number=4) - + single_utterance = proto.Field(proto.BOOL, number=4,) output_audio_config = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.OutputAudioConfig, ) - output_audio_config_mask = proto.Field( - proto.MESSAGE, number=7, message=field_mask.FieldMask, + proto.MESSAGE, number=7, message=field_mask_pb2.FieldMask, ) - - input_audio = proto.Field(proto.BYTES, number=6) + input_audio = proto.Field(proto.BYTES, number=6,) class StreamingDetectIntentResponse(proto.Message): @@ -732,22 +677,16 @@ class StreamingDetectIntentResponse(proto.Message): generate the output audio. """ - response_id = proto.Field(proto.STRING, number=1) - + response_id = proto.Field(proto.STRING, number=1,) recognition_result = proto.Field( proto.MESSAGE, number=2, message="StreamingRecognitionResult", ) - query_result = proto.Field(proto.MESSAGE, number=3, message="QueryResult",) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=7, message="QueryResult", ) - - webhook_status = proto.Field(proto.MESSAGE, number=4, message=status.Status,) - - output_audio = proto.Field(proto.BYTES, number=5) - + webhook_status = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) + output_audio = proto.Field(proto.BYTES, number=5,) output_audio_config = proto.Field( proto.MESSAGE, number=6, message=gcd_audio_config.OutputAudioConfig, ) @@ -841,21 +780,16 @@ 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=gcd_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, + ) dtmf_digits = proto.Field( proto.MESSAGE, number=5, message=gcd_audio_config.TelephonyDtmfEvents, ) @@ -863,7 +797,6 @@ class MessageType(proto.Enum): class TextInput(proto.Message): r"""Represents the natural language text to be processed. - Attributes: text (str): Required. The UTF-8 encoded natural language @@ -878,9 +811,8 @@ class TextInput(proto.Message): specify the same language. """ - text = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + text = proto.Field(proto.STRING, number=1,) + language_code = proto.Field(proto.STRING, number=2,) class EventInput(proto.Message): @@ -922,16 +854,13 @@ class EventInput(proto.Message): specify the same language. """ - name = proto.Field(proto.STRING, number=1) - - parameters = proto.Field(proto.MESSAGE, number=2, message=struct.Struct,) - - language_code = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + parameters = proto.Field(proto.MESSAGE, number=2, message=struct_pb2.Struct,) + language_code = proto.Field(proto.STRING, number=3,) class SentimentAnalysisRequestConfig(proto.Message): r"""Configures the types of sentiment analysis to perform. - Attributes: analyze_query_text_sentiment (bool): Instructs the service to perform sentiment analysis on @@ -939,7 +868,7 @@ class SentimentAnalysisRequestConfig(proto.Message): performed on ``query_text``. """ - analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1) + analyze_query_text_sentiment = proto.Field(proto.BOOL, number=1,) class SentimentAnalysisResult(proto.Message): @@ -980,9 +909,8 @@ class Sentiment(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/dialogflow_v2beta1/types/session_entity_type.py b/google/cloud/dialogflow_v2beta1/types/session_entity_type.py index 2cf83c8da..a3d4a2838 100644 --- a/google/cloud/dialogflow_v2beta1/types/session_entity_type.py +++ b/google/cloud/dialogflow_v2beta1/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.dialogflow_v2beta1.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( @@ -79,10 +76,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=2, enum=EntityOverrideMode,) - entities = proto.RepeatedField( proto.MESSAGE, number=3, message=entity_type.EntityType.Entity, ) @@ -115,11 +110,9 @@ class ListSessionEntityTypesRequest(proto.Message): list request. """ - parent = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + 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): @@ -144,8 +137,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): @@ -168,7 +160,7 @@ class GetSessionEntityTypeRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class CreateSessionEntityTypeRequest(proto.Message): @@ -193,8 +185,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", ) @@ -215,8 +206,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): @@ -239,7 +231,7 @@ class DeleteSessionEntityTypeRequest(proto.Message): specified, we assume default '-' user. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/validation_result.py b/google/cloud/dialogflow_v2beta1/types/validation_result.py index 1371ba1ca..4bd7018e5 100644 --- a/google/cloud/dialogflow_v2beta1/types/validation_result.py +++ b/google/cloud/dialogflow_v2beta1/types/validation_result.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 ValidationError(proto.Message): r"""Represents a single validation error. - Attributes: severity (google.cloud.dialogflow_v2beta1.types.ValidationError.Severity): The severity of the error. @@ -63,15 +60,12 @@ class Severity(proto.Enum): CRITICAL = 4 severity = proto.Field(proto.ENUM, number=1, enum=Severity,) - - entries = proto.RepeatedField(proto.STRING, number=3) - - error_message = proto.Field(proto.STRING, number=4) + entries = proto.RepeatedField(proto.STRING, number=3,) + error_message = proto.Field(proto.STRING, number=4,) class ValidationResult(proto.Message): r"""Represents the output of agent validation. - Attributes: validation_errors (Sequence[google.cloud.dialogflow_v2beta1.types.ValidationError]): Contains all validation errors. diff --git a/google/cloud/dialogflow_v2beta1/types/version.py b/google/cloud/dialogflow_v2beta1/types/version.py new file mode 100644 index 000000000..623c33e1e --- /dev/null +++ b/google/cloud/dialogflow_v2beta1/types/version.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2beta1", + manifest={ + "Version", + "ListVersionsRequest", + "ListVersionsResponse", + "GetVersionRequest", + "CreateVersionRequest", + "UpdateVersionRequest", + "DeleteVersionRequest", + }, +) + + +class Version(proto.Message): + r"""You can create multiple versions of your agent and publish them to + separate environments. + + When you edit an agent, you are editing the draft agent. At any + point, you can save the draft agent as an agent version, which is an + immutable snapshot of your agent. + + When you save the draft agent, it is published to the default + environment. When you create agent versions, you can publish them to + custom environments. You can create a variety of custom environments + for: + + - testing + - development + - production + - etc. + + For more information, see the `versions and environments + guide `__. + + Attributes: + name (str): + Output only. The unique identifier of this agent version. + Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + description (str): + Optional. The developer-provided description + of this version. + version_number (int): + Output only. The sequential number of this + version. This field is read-only which means it + cannot be set by create and update methods. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of this + version. This field is read-only, i.e., it + cannot be set by create and update methods. + status (google.cloud.dialogflow_v2beta1.types.Version.VersionStatus): + Output only. The status of this version. This + field is read-only and cannot be set by create + and update methods. + """ + + class VersionStatus(proto.Enum): + r"""The status of a version.""" + VERSION_STATUS_UNSPECIFIED = 0 + IN_PROGRESS = 1 + READY = 2 + FAILED = 3 + + name = proto.Field(proto.STRING, number=1,) + description = proto.Field(proto.STRING, number=2,) + version_number = proto.Field(proto.INT32, number=3,) + create_time = proto.Field(proto.MESSAGE, number=4, message=timestamp_pb2.Timestamp,) + status = proto.Field(proto.ENUM, number=6, enum=VersionStatus,) + + +class ListVersionsRequest(proto.Message): + r"""The request message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + parent (str): + Required. The agent to list all versions from. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + parent = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) + + +class ListVersionsResponse(proto.Message): + r"""The response message for + [Versions.ListVersions][google.cloud.dialogflow.v2beta1.Versions.ListVersions]. + + Attributes: + versions (Sequence[google.cloud.dialogflow_v2beta1.types.Version]): + The list of agent versions. There will be a maximum number + of items returned based on the page_size field in the + request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + versions = proto.RepeatedField(proto.MESSAGE, number=1, message="Version",) + next_page_token = proto.Field(proto.STRING, number=2,) + + +class GetVersionRequest(proto.Message): + r"""The request message for + [Versions.GetVersion][google.cloud.dialogflow.v2beta1.Versions.GetVersion]. + + Attributes: + name (str): + Required. The name of the version. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +class CreateVersionRequest(proto.Message): + r"""The request message for + [Versions.CreateVersion][google.cloud.dialogflow.v2beta1.Versions.CreateVersion]. + + Attributes: + parent (str): + Required. The agent to create a version for. Supported + formats: + + - ``projects//agent`` + - ``projects//locations//agent`` + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to create. + """ + + parent = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.MESSAGE, number=2, message="Version",) + + +class UpdateVersionRequest(proto.Message): + r"""The request message for + [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion]. + + Attributes: + version (google.cloud.dialogflow_v2beta1.types.Version): + Required. The version to update. Supported formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The mask to control which fields + get updated. + """ + + version = proto.Field(proto.MESSAGE, number=1, message="Version",) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) + + +class DeleteVersionRequest(proto.Message): + r"""The request message for + [Versions.DeleteVersion][google.cloud.dialogflow.v2beta1.Versions.DeleteVersion]. + + Attributes: + name (str): + Required. The name of the version to delete. Supported + formats: + + - ``projects//agent/versions/`` + - ``projects//locations//agent/versions/`` + """ + + name = proto.Field(proto.STRING, number=1,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/dialogflow_v2beta1/types/webhook.py b/google/cloud/dialogflow_v2beta1/types/webhook.py index 05ea8848d..cc7911ca4 100644 --- a/google/cloud/dialogflow_v2beta1/types/webhook.py +++ b/google/cloud/dialogflow_v2beta1/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,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import session as gcd_session from google.cloud.dialogflow_v2beta1.types import session_entity_type -from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -33,7 +30,6 @@ class WebhookRequest(proto.Message): r"""The request message for a webhook call. - Attributes: session (str): The unique identifier of detectIntent request session. Can @@ -59,18 +55,14 @@ class WebhookRequest(proto.Message): passed to ``[Streaming]DetectIntent`` call. """ - session = proto.Field(proto.STRING, number=4) - - response_id = proto.Field(proto.STRING, number=1) - + session = proto.Field(proto.STRING, number=4,) + response_id = proto.Field(proto.STRING, number=1,) query_result = proto.Field( proto.MESSAGE, number=2, message=gcd_session.QueryResult, ) - alternative_query_results = proto.RepeatedField( proto.MESSAGE, number=5, message=gcd_session.QueryResult, ) - original_detect_intent_request = proto.Field( proto.MESSAGE, number=3, message="OriginalDetectIntentRequest", ) @@ -157,28 +149,20 @@ class WebhookResponse(proto.Message): management methods. """ - fulfillment_text = proto.Field(proto.STRING, number=1) - + fulfillment_text = proto.Field(proto.STRING, number=1,) fulfillment_messages = proto.RepeatedField( proto.MESSAGE, number=2, message=intent.Intent.Message, ) - - source = proto.Field(proto.STRING, number=3) - - payload = proto.Field(proto.MESSAGE, number=4, message=struct.Struct,) - + source = proto.Field(proto.STRING, number=3,) + payload = proto.Field(proto.MESSAGE, number=4, message=struct_pb2.Struct,) output_contexts = proto.RepeatedField( proto.MESSAGE, number=5, message=context.Context, ) - followup_event_input = proto.Field( proto.MESSAGE, number=6, message=gcd_session.EventInput, ) - - live_agent_handoff = proto.Field(proto.BOOL, number=7) - - end_interaction = proto.Field(proto.BOOL, number=8) - + live_agent_handoff = proto.Field(proto.BOOL, number=7,) + end_interaction = proto.Field(proto.BOOL, number=8,) session_entity_types = proto.RepeatedField( proto.MESSAGE, number=10, message=session_entity_type.SessionEntityType, ) @@ -218,11 +202,9 @@ class OriginalDetectIntentRequest(proto.Message): Essentials Edition agents. """ - source = proto.Field(proto.STRING, number=1) - - version = proto.Field(proto.STRING, number=2) - - payload = proto.Field(proto.MESSAGE, number=3, message=struct.Struct,) + source = proto.Field(proto.STRING, number=1,) + version = proto.Field(proto.STRING, number=2,) + payload = proto.Field(proto.MESSAGE, number=3, message=struct_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/scripts/fixup_dialogflow_v2_keywords.py b/scripts/fixup_dialogflow_v2_keywords.py index a6f9a0f0c..cc0f68eb9 100644 --- a/scripts/fixup_dialogflow_v2_keywords.py +++ b/scripts/fixup_dialogflow_v2_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,77 +39,88 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'reload_document': ('name', 'content_uri', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'list_answer_records': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'content_uri', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -142,7 +151,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_dialogflow_v2beta1_keywords.py b/scripts/fixup_dialogflow_v2beta1_keywords.py index edac9dea1..0a8e20f0b 100644 --- a/scripts/fixup_dialogflow_v2beta1_keywords.py +++ b/scripts/fixup_dialogflow_v2beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,83 +39,94 @@ def partition( class dialogflowCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), - 'batch_create_entities': ('parent', 'entities', 'language_code', ), - 'batch_create_messages': ('parent', 'requests', ), - 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), - 'batch_delete_entity_types': ('parent', 'entity_type_names', ), - 'batch_delete_intents': ('parent', 'intents', ), - 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), - 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), - 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), - 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), - 'complete_conversation': ('name', ), - 'create_context': ('parent', 'context', ), - 'create_conversation': ('parent', 'conversation', 'conversation_id', ), - 'create_conversation_profile': ('parent', 'conversation_profile', ), - 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), - 'create_entity_type': ('parent', 'entity_type', 'language_code', ), - 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), - 'create_knowledge_base': ('parent', 'knowledge_base', ), - 'create_participant': ('parent', 'participant', ), - 'create_session_entity_type': ('parent', 'session_entity_type', ), - 'delete_agent': ('parent', ), - 'delete_all_contexts': ('parent', ), - 'delete_context': ('name', ), - 'delete_conversation_profile': ('name', ), - 'delete_document': ('name', ), - 'delete_entity_type': ('name', ), - 'delete_intent': ('name', ), - 'delete_knowledge_base': ('name', 'force', ), - 'delete_session_entity_type': ('name', ), - 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'export_agent': ('parent', 'agent_uri', ), - 'get_agent': ('parent', ), - 'get_answer_record': ('name', ), - 'get_context': ('name', ), - 'get_conversation': ('name', ), - 'get_conversation_profile': ('name', ), - 'get_document': ('name', ), - 'get_entity_type': ('name', 'language_code', ), - 'get_intent': ('name', 'language_code', 'intent_view', ), - 'get_knowledge_base': ('name', ), - 'get_participant': ('name', ), - 'get_session_entity_type': ('name', ), - 'get_validation_result': ('parent', 'language_code', ), - 'import_agent': ('parent', 'agent_uri', 'agent_content', ), - 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), - 'list_answer_records': ('parent', 'page_size', 'page_token', ), - 'list_contexts': ('parent', 'page_size', 'page_token', ), - 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), - 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), - 'list_participants': ('parent', 'page_size', 'page_token', ), - 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), - 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), - 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), - 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), - 'search_agents': ('parent', 'page_size', 'page_token', ), - 'set_agent': ('agent', 'update_mask', ), - 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), - 'suggest_articles': ('parent', 'latest_message', 'context_size', ), - 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), - 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), - 'train_agent': ('parent', ), - 'update_answer_record': ('answer_record', 'update_mask', ), - 'update_context': ('context', 'update_mask', ), - 'update_conversation_profile': ('conversation_profile', 'update_mask', ), - 'update_document': ('document', 'update_mask', ), - 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), - 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), - 'update_knowledge_base': ('knowledge_base', 'update_mask', ), - 'update_participant': ('participant', 'update_mask', ), - 'update_session_entity_type': ('session_entity_type', 'update_mask', ), - + 'analyze_content': ('participant', 'text_input', 'event_input', 'reply_audio_config', 'query_params', 'message_send_time', 'request_id', ), + 'batch_create_entities': ('parent', 'entities', 'language_code', ), + 'batch_create_messages': ('parent', 'requests', ), + 'batch_delete_entities': ('parent', 'entity_values', 'language_code', ), + 'batch_delete_entity_types': ('parent', 'entity_type_names', ), + 'batch_delete_intents': ('parent', 'intents', ), + 'batch_update_entities': ('parent', 'entities', 'language_code', 'update_mask', ), + 'batch_update_entity_types': ('parent', 'entity_type_batch_uri', 'entity_type_batch_inline', 'language_code', 'update_mask', ), + 'batch_update_intents': ('parent', 'intent_batch_uri', 'intent_batch_inline', 'language_code', 'update_mask', 'intent_view', ), + 'compile_suggestion': ('parent', 'latest_message', 'context_size', ), + 'complete_conversation': ('name', ), + 'create_context': ('parent', 'context', ), + 'create_conversation': ('parent', 'conversation', 'conversation_id', ), + 'create_conversation_profile': ('parent', 'conversation_profile', ), + 'create_document': ('parent', 'document', 'import_gcs_custom_metadata', ), + 'create_entity_type': ('parent', 'entity_type', 'language_code', ), + 'create_environment': ('parent', 'environment', 'environment_id', ), + 'create_intent': ('parent', 'intent', 'language_code', 'intent_view', ), + 'create_knowledge_base': ('parent', 'knowledge_base', ), + 'create_participant': ('parent', 'participant', ), + 'create_session_entity_type': ('parent', 'session_entity_type', ), + 'create_version': ('parent', 'version', ), + 'delete_agent': ('parent', ), + 'delete_all_contexts': ('parent', ), + 'delete_context': ('name', ), + 'delete_conversation_profile': ('name', ), + 'delete_document': ('name', ), + 'delete_entity_type': ('name', ), + 'delete_environment': ('name', ), + 'delete_intent': ('name', ), + 'delete_knowledge_base': ('name', 'force', ), + 'delete_session_entity_type': ('name', ), + 'delete_version': ('name', ), + 'detect_intent': ('session', 'query_input', 'query_params', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'export_agent': ('parent', 'agent_uri', ), + 'get_agent': ('parent', ), + 'get_answer_record': ('name', ), + 'get_context': ('name', ), + 'get_conversation': ('name', ), + 'get_conversation_profile': ('name', ), + 'get_document': ('name', ), + 'get_entity_type': ('name', 'language_code', ), + 'get_environment': ('name', ), + 'get_environment_history': ('parent', 'page_size', 'page_token', ), + 'get_fulfillment': ('name', ), + 'get_intent': ('name', 'language_code', 'intent_view', ), + 'get_knowledge_base': ('name', ), + 'get_participant': ('name', ), + 'get_session_entity_type': ('name', ), + 'get_validation_result': ('parent', 'language_code', ), + 'get_version': ('name', ), + 'import_agent': ('parent', 'agent_uri', 'agent_content', ), + 'import_documents': ('parent', 'document_template', 'gcs_source', 'import_gcs_custom_metadata', ), + 'list_answer_records': ('parent', 'page_size', 'page_token', ), + 'list_contexts': ('parent', 'page_size', 'page_token', ), + 'list_conversation_profiles': ('parent', 'page_size', 'page_token', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_entity_types': ('parent', 'language_code', 'page_size', 'page_token', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_intents': ('parent', 'language_code', 'intent_view', 'page_size', 'page_token', ), + 'list_knowledge_bases': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_messages': ('parent', 'filter', 'page_size', 'page_token', ), + 'list_participants': ('parent', 'page_size', 'page_token', ), + 'list_session_entity_types': ('parent', 'page_size', 'page_token', ), + 'list_suggestions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_versions': ('parent', 'page_size', 'page_token', ), + 'reload_document': ('name', 'gcs_source', 'import_gcs_custom_metadata', ), + 'restore_agent': ('parent', 'agent_uri', 'agent_content', ), + 'search_agents': ('parent', 'page_size', 'page_token', ), + 'set_agent': ('agent', 'update_mask', ), + 'streaming_detect_intent': ('session', 'query_input', 'query_params', 'single_utterance', 'output_audio_config', 'output_audio_config_mask', 'input_audio', ), + 'suggest_articles': ('parent', 'latest_message', 'context_size', ), + 'suggest_faq_answers': ('parent', 'latest_message', 'context_size', ), + 'suggest_smart_replies': ('parent', 'current_text_input', 'latest_message', 'context_size', ), + 'train_agent': ('parent', ), + 'update_answer_record': ('answer_record', 'update_mask', ), + 'update_context': ('context', 'update_mask', ), + 'update_conversation_profile': ('conversation_profile', 'update_mask', ), + 'update_document': ('document', 'update_mask', ), + 'update_entity_type': ('entity_type', 'language_code', 'update_mask', ), + 'update_environment': ('environment', 'update_mask', 'allow_load_to_draft_and_discard_changes', ), + 'update_fulfillment': ('fulfillment', 'update_mask', ), + 'update_intent': ('intent', 'language_code', 'update_mask', 'intent_view', ), + 'update_knowledge_base': ('knowledge_base', 'update_mask', ), + 'update_participant': ('participant', 'update_mask', ), + 'update_session_entity_type': ('session_entity_type', 'update_mask', ), + 'update_version': ('version', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -148,7 +157,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..4de65971c --- /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 000000000..4de65971c --- /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 000000000..4de65971c --- /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/dialogflow_v2/__init__.py b/tests/unit/gapic/dialogflow_v2/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/dialogflow_v2/__init__.py +++ b/tests/unit/gapic/dialogflow_v2/__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/dialogflow_v2/test_agents.py b/tests/unit/gapic/dialogflow_v2/test_agents.py index 12e3d6800..54f7f7612 100644 --- a/tests/unit/gapic/dialogflow_v2/test_agents.py +++ b/tests/unit/gapic/dialogflow_v2/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,56 @@ 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.dialogflow_v2.services.agents import AgentsAsyncClient from google.cloud.dialogflow_v2.services.agents import AgentsClient from google.cloud.dialogflow_v2.services.agents import pagers from google.cloud.dialogflow_v2.services.agents import transports +from google.cloud.dialogflow_v2.services.agents.transports.base import _API_CORE_VERSION +from google.cloud.dialogflow_v2.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import agent from google.cloud.dialogflow_v2.types import agent as gcd_agent from google.cloud.dialogflow_v2.types import validation_result 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 +115,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 +130,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 +173,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 +445,7 @@ def test_agents_client_client_options_from_dict(): 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, @@ -442,41 +469,26 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): api_version=agent.Agent.ApiVersion.API_VERSION_V1, tier=agent.Agent.Tier.TIER_STANDARD, ) - 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.parent == "parent_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.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -488,7 +500,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. @@ -496,7 +508,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -505,7 +516,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, @@ -531,40 +542,26 @@ async def test_get_agent_async( tier=agent.Agent.Tier.TIER_STANDARD, ) ) - 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.parent == "parent_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.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -574,17 +571,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.parent = "parent/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. @@ -599,17 +596,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.parent = "parent/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. @@ -623,13 +620,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(parent="parent_value",) @@ -638,12 +634,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_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. @@ -655,7 +650,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: @@ -671,13 +666,12 @@ async def test_get_agent_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_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. @@ -689,7 +683,7 @@ async def test_get_agent_flattened_error_async(): def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentRequest): 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, @@ -713,41 +707,26 @@ def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentReque api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) - response = client.set_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] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_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.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -759,7 +738,7 @@ def test_set_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. @@ -767,7 +746,6 @@ def test_set_agent_empty_call(): client.set_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() @@ -776,7 +754,7 @@ async def test_set_agent_async( transport: str = "grpc_asyncio", request_type=gcd_agent.SetAgentRequest ): 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, @@ -802,40 +780,26 @@ async def test_set_agent_async( tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_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.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -845,17 +809,17 @@ async def test_set_agent_async_from_dict(): def test_set_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 = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = gcd_agent.Agent() - client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +836,17 @@ def test_set_agent_field_headers(): @pytest.mark.asyncio async def test_set_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 = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -898,13 +862,12 @@ async def test_set_agent_field_headers_async(): def test_set_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.set_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_agent(agent=gcd_agent.Agent(parent="parent_value"),) @@ -913,12 +876,11 @@ def test_set_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") def test_set_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. @@ -930,7 +892,7 @@ def test_set_agent_flattened_error(): @pytest.mark.asyncio async def test_set_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.set_agent), "__call__") as call: @@ -946,13 +908,12 @@ async def test_set_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") @pytest.mark.asyncio async def test_set_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. @@ -964,7 +925,7 @@ async def test_set_agent_flattened_error_async(): 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, @@ -975,13 +936,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. @@ -996,7 +955,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. @@ -1004,7 +963,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1013,7 +971,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, @@ -1024,13 +982,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. @@ -1043,17 +999,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.parent = "parent/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. @@ -1068,17 +1024,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.parent = "parent/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. @@ -1092,13 +1048,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(parent="parent_value",) @@ -1107,12 +1062,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_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. @@ -1124,7 +1078,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: @@ -1140,13 +1094,12 @@ async def test_delete_agent_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_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. @@ -1158,7 +1111,7 @@ async def test_delete_agent_flattened_error_async(): def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsRequest): 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, @@ -1171,19 +1124,15 @@ def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsR call.return_value = agent.SearchAgentsResponse( next_page_token="next_page_token_value", ) - response = client.search_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.SearchAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -1195,7 +1144,7 @@ def test_search_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. @@ -1203,7 +1152,6 @@ def test_search_agents_empty_call(): client.search_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() @@ -1212,7 +1160,7 @@ async def test_search_agents_async( transport: str = "grpc_asyncio", request_type=agent.SearchAgentsRequest ): 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, @@ -1225,18 +1173,15 @@ async def test_search_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.search_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.SearchAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1246,17 +1191,17 @@ async def test_search_agents_async_from_dict(): def test_search_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.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: call.return_value = agent.SearchAgentsResponse() - client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1271,11 +1216,12 @@ def test_search_agents_field_headers(): @pytest.mark.asyncio async def test_search_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.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1229,6 @@ async def test_search_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse() ) - await client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1297,13 +1242,12 @@ async def test_search_agents_field_headers_async(): def test_search_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.search_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.SearchAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_agents(parent="parent_value",) @@ -1312,12 +1256,11 @@ def test_search_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_search_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. @@ -1329,7 +1272,7 @@ def test_search_agents_flattened_error(): @pytest.mark.asyncio async def test_search_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.search_agents), "__call__") as call: @@ -1347,13 +1290,12 @@ async def test_search_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_search_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. @@ -1364,7 +1306,7 @@ async def test_search_agents_flattened_error_async(): def test_search_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.search_agents), "__call__") as call: @@ -1394,7 +1336,7 @@ def test_search_agents_pager(): def test_search_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.search_agents), "__call__") as call: @@ -1416,7 +1358,7 @@ def test_search_agents_pages(): @pytest.mark.asyncio async def test_search_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( @@ -1445,7 +1387,7 @@ async def test_search_agents_async_pager(): @pytest.mark.asyncio async def test_search_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( @@ -1471,7 +1413,7 @@ async def test_search_agents_async_pages(): def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentRequest): 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, @@ -1482,13 +1424,11 @@ def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentReque with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_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.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1503,7 +1443,7 @@ def test_train_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. @@ -1511,7 +1451,6 @@ def test_train_agent_empty_call(): client.train_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() @@ -1520,7 +1459,7 @@ async def test_train_agent_async( transport: str = "grpc_asyncio", request_type=agent.TrainAgentRequest ): 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, @@ -1533,13 +1472,11 @@ async def test_train_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_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.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1552,17 +1489,17 @@ async def test_train_agent_async_from_dict(): def test_train_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.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1577,11 +1514,12 @@ def test_train_agent_field_headers(): @pytest.mark.asyncio async def test_train_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.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1527,6 @@ async def test_train_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1603,13 +1540,12 @@ async def test_train_agent_field_headers_async(): def test_train_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.train_agent), "__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_agent(parent="parent_value",) @@ -1618,12 +1554,11 @@ def test_train_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_train_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. @@ -1635,7 +1570,7 @@ def test_train_agent_flattened_error(): @pytest.mark.asyncio async def test_train_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.train_agent), "__call__") as call: @@ -1653,13 +1588,12 @@ async def test_train_agent_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_train_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. @@ -1671,7 +1605,7 @@ async def test_train_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, @@ -1682,13 +1616,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. @@ -1703,7 +1635,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. @@ -1711,7 +1643,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1720,7 +1651,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, @@ -1733,13 +1664,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. @@ -1752,17 +1681,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.parent = "parent/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. @@ -1777,11 +1706,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.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1789,7 +1719,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. @@ -1803,13 +1732,12 @@ async def test_export_agent_field_headers_async(): def test_export_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.export_agent), "__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.export_agent(parent="parent_value",) @@ -1818,12 +1746,11 @@ def test_export_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_export_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. @@ -1835,7 +1762,7 @@ def test_export_agent_flattened_error(): @pytest.mark.asyncio async def test_export_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.export_agent), "__call__") as call: @@ -1853,13 +1780,12 @@ async def test_export_agent_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_export_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. @@ -1871,7 +1797,7 @@ async def test_export_agent_flattened_error_async(): def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentRequest): 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, @@ -1882,13 +1808,11 @@ def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentReq with mock.patch.object(type(client.transport.import_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_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.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1903,7 +1827,7 @@ def test_import_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. @@ -1911,7 +1835,6 @@ def test_import_agent_empty_call(): client.import_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() @@ -1920,7 +1843,7 @@ async def test_import_agent_async( transport: str = "grpc_asyncio", request_type=agent.ImportAgentRequest ): 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, @@ -1933,13 +1856,11 @@ async def test_import_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_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.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1952,17 +1873,17 @@ async def test_import_agent_async_from_dict(): def test_import_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.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1977,11 +1898,12 @@ def test_import_agent_field_headers(): @pytest.mark.asyncio async def test_import_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.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1911,6 @@ async def test_import_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2004,7 +1925,7 @@ async def test_import_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, @@ -2015,13 +1936,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. @@ -2036,7 +1955,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. @@ -2044,7 +1963,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -2053,7 +1971,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, @@ -2066,13 +1984,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. @@ -2085,17 +2001,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.parent = "parent/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. @@ -2110,11 +2026,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.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2122,7 +2039,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. @@ -2139,7 +2055,7 @@ def test_get_validation_result( transport: str = "grpc", request_type=agent.GetValidationResultRequest ): 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, @@ -2152,17 +2068,14 @@ def test_get_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = validation_result.ValidationResult() - response = client.get_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.GetValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) @@ -2174,7 +2087,7 @@ def test_get_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. @@ -2184,7 +2097,6 @@ def test_get_validation_result_empty_call(): client.get_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() @@ -2193,7 +2105,7 @@ async def test_get_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetValidationResultRequest ): 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, @@ -2208,13 +2120,11 @@ async def test_get_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - response = await client.get_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.GetValidationResultRequest() # Establish that the response is the type that we expect. @@ -2227,11 +2137,12 @@ async def test_get_validation_result_async_from_dict(): def test_get_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.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2239,7 +2150,6 @@ def test_get_validation_result_field_headers(): type(client.transport.get_validation_result), "__call__" ) as call: call.return_value = validation_result.ValidationResult() - client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2254,11 +2164,12 @@ def test_get_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_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.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2268,7 +2179,6 @@ async def test_get_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2284,16 +2194,16 @@ async def test_get_validation_result_field_headers_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( @@ -2303,7 +2213,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( @@ -2314,7 +2224,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 @@ -2323,13 +2233,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 @@ -2341,23 +2251,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", ) @@ -2369,7 +2279,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 @@ -2395,15 +2305,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.dialogflow_v2.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.dialogflow_v2.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", ) @@ -2419,19 +2354,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.dialogflow_v2.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=( @@ -2442,14 +2394,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", @@ -2459,12 +2435,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", + 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", + 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: @@ -2506,7 +2593,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" ), @@ -2516,7 +2603,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" ), @@ -2567,9 +2654,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", @@ -2648,7 +2735,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 @@ -2661,7 +2748,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 @@ -2674,7 +2761,6 @@ def test_agents_grpc_lro_async_client(): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = AgentsClient.agent_path(project) assert expected == actual @@ -2693,7 +2779,6 @@ def test_parse_agent_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2714,7 +2799,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2733,7 +2817,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2752,7 +2835,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2772,7 +2854,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2799,7 +2880,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) @@ -2808,6 +2889,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/dialogflow_v2/test_answer_records.py b/tests/unit/gapic/dialogflow_v2/test_answer_records.py index 39c5932a3..05fbde42a 100644 --- a/tests/unit/gapic/dialogflow_v2/test_answer_records.py +++ b/tests/unit/gapic/dialogflow_v2/test_answer_records.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.dialogflow_v2.services.answer_records import AnswerRecordsAsyncClient from google.cloud.dialogflow_v2.services.answer_records import AnswerRecordsClient from google.cloud.dialogflow_v2.services.answer_records import pagers from google.cloud.dialogflow_v2.services.answer_records import transports +from google.cloud.dialogflow_v2.services.answer_records.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.answer_records.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record from google.cloud.dialogflow_v2.types import participant from google.oauth2 import service_account -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 +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(): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_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: @@ -109,7 +138,7 @@ def test_answer_records_client_from_service_account_info(client_class): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_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: @@ -162,7 +191,7 @@ def test_answer_records_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AnswerRecordsClient, "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() @@ -450,7 +479,7 @@ def test_list_answer_records( transport: str = "grpc", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,19 +494,15 @@ def test_list_answer_records( call.return_value = answer_record.ListAnswerRecordsResponse( next_page_token="next_page_token_value", ) - response = client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == "next_page_token_value" @@ -489,7 +514,7 @@ def test_list_answer_records_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 = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -499,7 +524,6 @@ def test_list_answer_records_empty_call(): client.list_answer_records() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() @@ -508,7 +532,7 @@ async def test_list_answer_records_async( transport: str = "grpc_asyncio", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -525,18 +549,15 @@ async def test_list_answer_records_async( next_page_token="next_page_token_value", ) ) - response = await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -546,11 +567,12 @@ async def test_list_answer_records_async_from_dict(): def test_list_answer_records_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -558,7 +580,6 @@ def test_list_answer_records_field_headers(): type(client.transport.list_answer_records), "__call__" ) as call: call.return_value = answer_record.ListAnswerRecordsResponse() - client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -573,11 +594,14 @@ def test_list_answer_records_field_headers(): @pytest.mark.asyncio async def test_list_answer_records_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -587,7 +611,6 @@ async def test_list_answer_records_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.ListAnswerRecordsResponse() ) - await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -601,7 +624,7 @@ async def test_list_answer_records_field_headers_async(): def test_list_answer_records_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -609,7 +632,6 @@ def test_list_answer_records_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = answer_record.ListAnswerRecordsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_answer_records(parent="parent_value",) @@ -618,12 +640,11 @@ def test_list_answer_records_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -635,7 +656,9 @@ def test_list_answer_records_flattened_error(): @pytest.mark.asyncio async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -655,13 +678,14 @@ async def test_list_answer_records_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_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -672,7 +696,7 @@ async def test_list_answer_records_flattened_error_async(): def test_list_answer_records_pager(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -717,7 +741,7 @@ def test_list_answer_records_pager(): def test_list_answer_records_pages(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -754,7 +778,7 @@ def test_list_answer_records_pages(): @pytest.mark.asyncio async def test_list_answer_records_async_pager(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -798,7 +822,7 @@ async def test_list_answer_records_async_pager(): @pytest.mark.asyncio async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -841,7 +865,7 @@ def test_update_answer_record( transport: str = "grpc", request_type=gcd_answer_record.UpdateAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -859,19 +883,15 @@ def test_update_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -883,7 +903,7 @@ def test_update_answer_record_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 = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -893,7 +913,6 @@ def test_update_answer_record_empty_call(): client.update_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() @@ -903,7 +922,7 @@ async def test_update_answer_record_async( request_type=gcd_answer_record.UpdateAnswerRecordRequest, ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -918,18 +937,15 @@ async def test_update_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord(name="name_value",) ) - response = await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -939,11 +955,12 @@ async def test_update_answer_record_async_from_dict(): def test_update_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -951,7 +968,6 @@ def test_update_answer_record_field_headers(): type(client.transport.update_answer_record), "__call__" ) as call: call.return_value = gcd_answer_record.AnswerRecord() - client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -969,11 +985,14 @@ def test_update_answer_record_field_headers(): @pytest.mark.asyncio async def test_update_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -983,7 +1002,6 @@ async def test_update_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord() ) - await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1000,7 +1018,7 @@ async def test_update_answer_record_field_headers_async(): def test_update_answer_record_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1008,28 +1026,25 @@ def test_update_answer_record_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_answer_record.AnswerRecord() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(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].answer_record == gcd_answer_record.AnswerRecord( 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_answer_record_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1037,13 +1052,15 @@ def test_update_answer_record_flattened_error(): client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(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_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1059,24 +1076,24 @@ async def test_update_answer_record_flattened_async(): # using the keyword arguments to the method. response = await client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(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].answer_record == gcd_answer_record.AnswerRecord( 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_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1084,23 +1101,23 @@ async def test_update_answer_record_flattened_error_async(): await client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( - 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.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1110,7 +1127,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1121,7 +1138,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AnswerRecordsClient(transport=transport) assert client.transport is transport @@ -1130,13 +1147,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1151,23 +1168,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 = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AnswerRecordsGrpcTransport,) def test_answer_records_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.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1179,7 +1196,7 @@ def test_answer_records_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1193,15 +1210,40 @@ def test_answer_records_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_answer_records_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.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnswerRecordsTransport( + 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_answer_records_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.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._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.AnswerRecordsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1217,19 +1259,36 @@ def test_answer_records_base_transport_with_credentials_file(): def test_answer_records_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.dialogflow_v2.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_answer_records_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) + AnswerRecordsClient() + 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_answer_records_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) AnswerRecordsClient() adc.assert_called_once_with( scopes=( @@ -1240,14 +1299,44 @@ def test_answer_records_auth_adc(): ) -def test_answer_records_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_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.AnswerRecordsGrpcTransport( - 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.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_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", @@ -1257,6 +1346,121 @@ def test_answer_records_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_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.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_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", + 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.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_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", + 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", [ @@ -1265,7 +1469,7 @@ def test_answer_records_transport_auth_adc(): ], ) def test_answer_records_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: @@ -1307,7 +1511,7 @@ def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_cla def test_answer_records_host_no_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1317,7 +1521,7 @@ def test_answer_records_host_no_port(): def test_answer_records_host_with_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1371,9 +1575,9 @@ def test_answer_records_transport_channel_mtls_with_client_cert_source(transport 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", @@ -1456,7 +1660,6 @@ def test_answer_records_transport_channel_mtls_with_adc(transport_class): def test_answer_record_path(): project = "squid" answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format( project=project, answer_record=answer_record, ) @@ -1478,7 +1681,6 @@ def test_parse_answer_record_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1499,7 +1701,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AnswerRecordsClient.common_folder_path(folder) assert expected == actual @@ -1518,7 +1719,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AnswerRecordsClient.common_organization_path(organization) assert expected == actual @@ -1537,7 +1737,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AnswerRecordsClient.common_project_path(project) assert expected == actual @@ -1557,7 +1756,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, ) @@ -1584,7 +1782,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AnswerRecordsTransport, "_prep_wrapped_messages" ) as prep: client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1593,6 +1791,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AnswerRecordsClient.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/dialogflow_v2/test_contexts.py b/tests/unit/gapic/dialogflow_v2/test_contexts.py index 8d2548366..2a767e850 100644 --- a/tests/unit/gapic/dialogflow_v2/test_contexts.py +++ b/tests/unit/gapic/dialogflow_v2/test_contexts.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.dialogflow_v2.services.contexts import ContextsAsyncClient from google.cloud.dialogflow_v2.services.contexts import ContextsClient from google.cloud.dialogflow_v2.services.contexts import pagers from google.cloud.dialogflow_v2.services.contexts import transports +from google.cloud.dialogflow_v2.services.contexts.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.contexts.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import context as gcd_context 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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_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_contexts_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_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_contexts_client_get_transport_class(): def test_contexts_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(ContextsClient, "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_contexts( transport: str = "grpc", request_type=context.ListContextsRequest ): client = ContextsClient( - 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_contexts( call.return_value = context.ListContextsResponse( next_page_token="next_page_token_value", ) - response = client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_contexts_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 = ContextsClient( - 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_contexts_empty_call(): client.list_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() @@ -474,7 +498,7 @@ async def test_list_contexts_async( transport: str = "grpc_asyncio", request_type=context.ListContextsRequest ): client = ContextsAsyncClient( - 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_contexts_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContextsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_contexts_async_from_dict(): def test_list_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: call.return_value = context.ListContextsResponse() - client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_contexts_field_headers(): @pytest.mark.asyncio async def test_list_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_contexts_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse() ) - await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_contexts_field_headers_async(): def test_list_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.ListContextsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_contexts(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(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_contexts_flattened_error(): @pytest.mark.asyncio async def test_list_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_contexts_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_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(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_contexts_flattened_error_async(): def test_list_contexts_pager(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_contexts_pager(): def test_list_contexts_pages(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_contexts_pages(): @pytest.mark.asyncio async def test_list_contexts_async_pager(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(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_contexts_async_pager(): @pytest.mark.asyncio async def test_list_contexts_async_pages(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(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_contexts_async_pages(): def test_get_context(transport: str = "grpc", request_type=context.GetContextRequest): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -760,21 +778,16 @@ def test_get_context(transport: str = "grpc", request_type=context.GetContextReq with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context(name="name_value", lifespan_count=1498,) - response = client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -786,7 +799,7 @@ def test_get_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -794,7 +807,6 @@ def test_get_context_empty_call(): client.get_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() @@ -803,7 +815,7 @@ async def test_get_context_async( transport: str = "grpc_asyncio", request_type=context.GetContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -816,20 +828,16 @@ async def test_get_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -839,17 +847,17 @@ async def test_get_context_async_from_dict(): def test_get_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = context.Context() - client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -864,17 +872,17 @@ def test_get_context_field_headers(): @pytest.mark.asyncio async def test_get_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - await client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -888,13 +896,12 @@ async def test_get_context_field_headers_async(): def test_get_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_context(name="name_value",) @@ -903,12 +910,11 @@ def test_get_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +926,7 @@ def test_get_context_flattened_error(): @pytest.mark.asyncio async def test_get_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: @@ -936,13 +942,12 @@ async def test_get_context_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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +961,7 @@ def test_create_context( transport: str = "grpc", request_type=gcd_context.CreateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,21 +972,16 @@ def test_create_context( with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -993,7 +993,7 @@ def test_create_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +1001,6 @@ def test_create_context_empty_call(): client.create_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() @@ -1010,7 +1009,7 @@ async def test_create_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.CreateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1023,20 +1022,16 @@ async def test_create_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1046,17 +1041,17 @@ async def test_create_context_async_from_dict(): def test_create_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = gcd_context.Context() - client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1071,17 +1066,17 @@ def test_create_context_field_headers(): @pytest.mark.asyncio async def test_create_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1095,13 +1090,12 @@ async def test_create_context_field_headers_async(): def test_create_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_context( @@ -1112,14 +1106,12 @@ def test_create_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") def test_create_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1133,7 +1125,7 @@ def test_create_context_flattened_error(): @pytest.mark.asyncio async def test_create_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: @@ -1151,15 +1143,13 @@ async def test_create_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") @pytest.mark.asyncio async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,7 +1165,7 @@ def test_update_context( transport: str = "grpc", request_type=gcd_context.UpdateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1186,21 +1176,16 @@ def test_update_context( with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1212,7 +1197,7 @@ def test_update_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1205,6 @@ def test_update_context_empty_call(): client.update_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() @@ -1229,7 +1213,7 @@ async def test_update_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.UpdateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,20 +1226,16 @@ async def test_update_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1265,17 +1245,17 @@ async def test_update_context_async_from_dict(): def test_update_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = gcd_context.Context() - client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1292,17 +1272,17 @@ def test_update_context_field_headers(): @pytest.mark.asyncio async def test_update_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1318,32 +1298,29 @@ async def test_update_context_field_headers_async(): def test_update_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_context( context=gcd_context.Context(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].context == gcd_context.Context(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_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1351,13 +1328,13 @@ def test_update_context_flattened_error(): client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(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_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: @@ -1369,22 +1346,20 @@ async def test_update_context_flattened_async(): # using the keyword arguments to the method. response = await client.update_context( context=gcd_context.Context(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].context == gcd_context.Context(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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1392,7 +1367,7 @@ async def test_update_context_flattened_error_async(): await client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1400,7 +1375,7 @@ def test_delete_context( transport: str = "grpc", request_type=context.DeleteContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1411,13 +1386,11 @@ def test_delete_context( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1432,7 +1405,7 @@ def test_delete_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1440,7 +1413,6 @@ def test_delete_context_empty_call(): client.delete_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() @@ -1449,7 +1421,7 @@ async def test_delete_context_async( transport: str = "grpc_asyncio", request_type=context.DeleteContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1460,13 +1432,11 @@ async def test_delete_context_async( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1479,17 +1449,17 @@ async def test_delete_context_async_from_dict(): def test_delete_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = None - client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1504,17 +1474,17 @@ def test_delete_context_field_headers(): @pytest.mark.asyncio async def test_delete_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1528,13 +1498,12 @@ async def test_delete_context_field_headers_async(): def test_delete_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__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_context(name="name_value",) @@ -1543,12 +1512,11 @@ def test_delete_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1560,7 +1528,7 @@ def test_delete_context_flattened_error(): @pytest.mark.asyncio async def test_delete_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: @@ -1576,13 +1544,12 @@ async def test_delete_context_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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,7 +1563,7 @@ def test_delete_all_contexts( transport: str = "grpc", request_type=context.DeleteAllContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1609,13 +1576,11 @@ def test_delete_all_contexts( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1630,7 +1595,7 @@ def test_delete_all_contexts_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1640,7 +1605,6 @@ def test_delete_all_contexts_empty_call(): client.delete_all_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() @@ -1649,7 +1613,7 @@ async def test_delete_all_contexts_async( transport: str = "grpc_asyncio", request_type=context.DeleteAllContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1626,11 @@ async def test_delete_all_contexts_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1681,11 +1643,12 @@ async def test_delete_all_contexts_async_from_dict(): def test_delete_all_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1656,6 @@ def test_delete_all_contexts_field_headers(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = None - client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1670,12 @@ def test_delete_all_contexts_field_headers(): @pytest.mark.asyncio async def test_delete_all_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1683,6 @@ async def test_delete_all_contexts_field_headers_async(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1734,7 +1696,7 @@ async def test_delete_all_contexts_field_headers_async(): def test_delete_all_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1742,7 +1704,6 @@ def test_delete_all_contexts_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_all_contexts(parent="parent_value",) @@ -1751,12 +1712,11 @@ def test_delete_all_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_all_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1768,7 +1728,7 @@ def test_delete_all_contexts_flattened_error(): @pytest.mark.asyncio async def test_delete_all_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1786,13 +1746,12 @@ async def test_delete_all_contexts_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_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1805,16 +1764,16 @@ async def test_delete_all_contexts_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( - 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.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1824,7 +1783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1835,7 +1794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ContextsClient(transport=transport) assert client.transport is transport @@ -1844,13 +1803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ContextsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1862,23 +1821,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 = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ContextsGrpcTransport,) def test_contexts_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.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1890,7 +1849,7 @@ def test_contexts_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1908,15 +1867,40 @@ def test_contexts_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_contexts_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.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + 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_contexts_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.dialogflow_v2.services.contexts.transports.ContextsTransport._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.ContextsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1932,19 +1916,36 @@ def test_contexts_base_transport_with_credentials_file(): def test_contexts_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.dialogflow_v2.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_contexts_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) + ContextsClient() + 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_contexts_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) ContextsClient() adc.assert_called_once_with( scopes=( @@ -1955,14 +1956,38 @@ def test_contexts_auth_adc(): ) -def test_contexts_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_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.ContextsGrpcTransport( - 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_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", @@ -1972,12 +1997,123 @@ def test_contexts_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_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.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_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", + 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.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_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", + 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport], ) def test_contexts_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: @@ -2019,7 +2155,7 @@ def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): def test_contexts_host_no_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2029,7 +2165,7 @@ def test_contexts_host_no_port(): def test_contexts_host_with_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2080,9 +2216,9 @@ def test_contexts_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", @@ -2163,7 +2299,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2186,7 +2321,6 @@ def test_parse_context_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2207,7 +2341,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = ContextsClient.common_folder_path(folder) assert expected == actual @@ -2226,7 +2359,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = ContextsClient.common_organization_path(organization) assert expected == actual @@ -2245,7 +2377,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = ContextsClient.common_project_path(project) assert expected == actual @@ -2265,7 +2396,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, ) @@ -2292,7 +2422,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ContextsTransport, "_prep_wrapped_messages" ) as prep: client = ContextsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2301,6 +2431,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ContextsClient.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/dialogflow_v2/test_conversation_profiles.py b/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py index d4ef7e529..694bfc17e 100644 --- a/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py +++ b/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.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.dialogflow_v2.services.conversation_profiles import ( ConversationProfilesAsyncClient, @@ -40,14 +39,44 @@ ) from google.cloud.dialogflow_v2.services.conversation_profiles import pagers from google.cloud.dialogflow_v2.services.conversation_profiles import transports +from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.conversation_profiles.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import conversation_profile from google.cloud.dialogflow_v2.types import ( conversation_profile as gcd_conversation_profile, ) from google.oauth2 import service_account -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 +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", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_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_conversation_profiles_client_from_service_account_info(client_class): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_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_conversation_profiles_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationProfilesClient, "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_list_conversation_profiles( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -495,19 +524,15 @@ def test_list_conversation_profiles( call.return_value = conversation_profile.ListConversationProfilesResponse( next_page_token="next_page_token_value", ) - response = client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == "next_page_token_value" @@ -519,7 +544,7 @@ def test_list_conversation_profiles_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -529,7 +554,6 @@ def test_list_conversation_profiles_empty_call(): client.list_conversation_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() @@ -539,7 +563,7 @@ async def test_list_conversation_profiles_async( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -556,18 +580,15 @@ async def test_list_conversation_profiles_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationProfilesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -577,11 +598,14 @@ async def test_list_conversation_profiles_async_from_dict(): def test_list_conversation_profiles_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -589,7 +613,6 @@ def test_list_conversation_profiles_field_headers(): type(client.transport.list_conversation_profiles), "__call__" ) as call: call.return_value = conversation_profile.ListConversationProfilesResponse() - client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -605,12 +628,13 @@ def test_list_conversation_profiles_field_headers(): @pytest.mark.asyncio async def test_list_conversation_profiles_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -620,7 +644,6 @@ async def test_list_conversation_profiles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ListConversationProfilesResponse() ) - await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -634,7 +657,9 @@ async def test_list_conversation_profiles_field_headers_async(): def test_list_conversation_profiles_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -642,7 +667,6 @@ def test_list_conversation_profiles_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ListConversationProfilesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversation_profiles(parent="parent_value",) @@ -651,12 +675,13 @@ def test_list_conversation_profiles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -670,7 +695,7 @@ def test_list_conversation_profiles_flattened_error(): @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,14 +716,13 @@ async def test_list_conversation_profiles_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_conversation_profiles_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -711,7 +735,9 @@ async def test_list_conversation_profiles_flattened_error_async(): def test_list_conversation_profiles_pager(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -759,7 +785,9 @@ def test_list_conversation_profiles_pager(): def test_list_conversation_profiles_pages(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -798,7 +826,7 @@ def test_list_conversation_profiles_pages(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pager(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -847,7 +875,7 @@ async def test_list_conversation_profiles_async_pager(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pages(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -893,7 +921,7 @@ def test_get_conversation_profile( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -910,23 +938,17 @@ def test_get_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -938,7 +960,7 @@ def test_get_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -948,7 +970,6 @@ def test_get_conversation_profile_empty_call(): client.get_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() @@ -958,7 +979,7 @@ async def test_get_conversation_profile_async( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -977,22 +998,17 @@ async def test_get_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1002,11 +1018,14 @@ async def test_get_conversation_profile_async_from_dict(): def test_get_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1014,7 +1033,6 @@ def test_get_conversation_profile_field_headers(): type(client.transport.get_conversation_profile), "__call__" ) as call: call.return_value = conversation_profile.ConversationProfile() - client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1030,12 +1048,13 @@ def test_get_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_get_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1045,7 +1064,6 @@ async def test_get_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ConversationProfile() ) - await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1059,7 +1077,9 @@ async def test_get_conversation_profile_field_headers_async(): def test_get_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1067,7 +1087,6 @@ def test_get_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation_profile(name="name_value",) @@ -1076,12 +1095,13 @@ def test_get_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1094,7 +1114,7 @@ def test_get_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1115,14 +1135,13 @@ async def test_get_conversation_profile_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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1138,7 +1157,7 @@ def test_create_conversation_profile( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1155,23 +1174,17 @@ def test_create_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1183,7 +1196,7 @@ def test_create_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1193,7 +1206,6 @@ def test_create_conversation_profile_empty_call(): client.create_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() @@ -1203,7 +1215,7 @@ async def test_create_conversation_profile_async( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,22 +1234,17 @@ async def test_create_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1247,11 +1254,14 @@ async def test_create_conversation_profile_async_from_dict(): def test_create_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1259,7 +1269,6 @@ def test_create_conversation_profile_field_headers(): type(client.transport.create_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1275,12 +1284,13 @@ def test_create_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_create_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1290,7 +1300,6 @@ async def test_create_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1304,7 +1313,9 @@ async def test_create_conversation_profile_field_headers_async(): def test_create_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1312,7 +1323,6 @@ def test_create_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation_profile( @@ -1326,9 +1336,7 @@ def test_create_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1337,7 +1345,9 @@ def test_create_conversation_profile_flattened(): def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1354,7 +1364,7 @@ def test_create_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1380,9 +1390,7 @@ async def test_create_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1393,7 +1401,7 @@ async def test_create_conversation_profile_flattened_async(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1413,7 +1421,7 @@ def test_update_conversation_profile( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1430,23 +1438,17 @@ def test_update_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1458,7 +1460,7 @@ def test_update_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1468,7 +1470,6 @@ def test_update_conversation_profile_empty_call(): client.update_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() @@ -1478,7 +1479,7 @@ async def test_update_conversation_profile_async( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1497,22 +1498,17 @@ async def test_update_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1522,11 +1518,14 @@ async def test_update_conversation_profile_async_from_dict(): def test_update_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1534,7 +1533,6 @@ def test_update_conversation_profile_field_headers(): type(client.transport.update_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1553,12 +1551,13 @@ def test_update_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_update_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1568,7 +1567,6 @@ async def test_update_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1585,7 +1583,9 @@ async def test_update_conversation_profile_field_headers_async(): def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1593,32 +1593,31 @@ def test_update_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_conversation_profile( conversation_profile=gcd_conversation_profile.ConversationProfile( 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 ].conversation_profile == gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1628,14 +1627,14 @@ def test_update_conversation_profile_flattened_error(): conversation_profile=gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1654,27 +1653,25 @@ async def test_update_conversation_profile_flattened_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( 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 ].conversation_profile == gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1685,7 +1682,7 @@ async def test_update_conversation_profile_flattened_error_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1694,7 +1691,7 @@ def test_delete_conversation_profile( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1707,13 +1704,11 @@ def test_delete_conversation_profile( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1728,7 +1723,7 @@ def test_delete_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1738,7 +1733,6 @@ def test_delete_conversation_profile_empty_call(): client.delete_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() @@ -1748,7 +1742,7 @@ async def test_delete_conversation_profile_async( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1761,13 +1755,11 @@ async def test_delete_conversation_profile_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1780,11 +1772,14 @@ async def test_delete_conversation_profile_async_from_dict(): def test_delete_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1792,7 +1787,6 @@ def test_delete_conversation_profile_field_headers(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = None - client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1808,12 +1802,13 @@ def test_delete_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_delete_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1821,7 +1816,6 @@ async def test_delete_conversation_profile_field_headers_async(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1835,7 +1829,9 @@ async def test_delete_conversation_profile_field_headers_async(): def test_delete_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1843,7 +1839,6 @@ def test_delete_conversation_profile_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_conversation_profile(name="name_value",) @@ -1852,12 +1847,13 @@ def test_delete_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1870,7 +1866,7 @@ def test_delete_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1889,14 +1885,13 @@ async def test_delete_conversation_profile_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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1910,16 +1905,16 @@ async def test_delete_conversation_profile_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( - 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.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1929,7 +1924,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1940,7 +1935,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationProfilesClient(transport=transport) assert client.transport is transport @@ -1949,13 +1944,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1970,23 +1965,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 = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.ConversationProfilesGrpcTransport,) def test_conversation_profiles_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.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1998,7 +1995,7 @@ def test_conversation_profiles_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2015,15 +2012,40 @@ def test_conversation_profiles_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_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.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._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.ConversationProfilesTransport( + 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_conversation_profiles_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.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2039,19 +2061,36 @@ def test_conversation_profiles_base_transport_with_credentials_file(): def test_conversation_profiles_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.dialogflow_v2.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_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) + ConversationProfilesClient() + 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_conversation_profiles_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) ConversationProfilesClient() adc.assert_called_once_with( scopes=( @@ -2062,14 +2101,44 @@ def test_conversation_profiles_auth_adc(): ) -def test_conversation_profiles_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_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.ConversationProfilesGrpcTransport( - 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.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_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", @@ -2079,6 +2148,121 @@ def test_conversation_profiles_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_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.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_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", + 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.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_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", + 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", [ @@ -2089,7 +2273,7 @@ def test_conversation_profiles_transport_auth_adc(): def test_conversation_profiles_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: @@ -2131,7 +2315,7 @@ def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( def test_conversation_profiles_host_no_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2141,7 +2325,7 @@ def test_conversation_profiles_host_no_port(): def test_conversation_profiles_host_with_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2197,9 +2381,9 @@ def test_conversation_profiles_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", @@ -2281,7 +2465,6 @@ def test_conversation_profiles_transport_channel_mtls_with_adc(transport_class): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = ConversationProfilesClient.agent_path(project) assert expected == actual @@ -2298,10 +2481,35 @@ def test_parse_agent_path(): assert expected == actual -def test_conversation_profile_path(): +def test_conversation_model_path(): project = "whelk" - conversation_profile = "octopus" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + actual = ConversationProfilesClient.conversation_model_path( + project, location, conversation_model + ) + assert expected == actual + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2313,8 +2521,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "oyster", - "conversation_profile": "nudibranch", + "project": "scallop", + "conversation_profile": "abalone", } path = ConversationProfilesClient.conversation_profile_path(**expected) @@ -2324,10 +2532,9 @@ def test_parse_conversation_profile_path(): def test_document_path(): - project = "cuttlefish" - knowledge_base = "mussel" - document = "winkle" - + project = "squid" + knowledge_base = "clam" + document = "whelk" expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2337,9 +2544,9 @@ def test_document_path(): def test_parse_document_path(): expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", } path = ConversationProfilesClient.document_path(**expected) @@ -2349,9 +2556,8 @@ def test_parse_document_path(): def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - + project = "cuttlefish" + knowledge_base = "mussel" expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2361,8 +2567,8 @@ def test_knowledge_base_path(): def test_parse_knowledge_base_path(): expected = { - "project": "whelk", - "knowledge_base": "octopus", + "project": "winkle", + "knowledge_base": "nautilus", } path = ConversationProfilesClient.knowledge_base_path(**expected) @@ -2372,8 +2578,7 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): - billing_account = "oyster" - + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2383,7 +2588,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = ConversationProfilesClient.common_billing_account_path(**expected) @@ -2393,8 +2598,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "squid" expected = "folders/{folder}".format(folder=folder,) actual = ConversationProfilesClient.common_folder_path(folder) assert expected == actual @@ -2402,7 +2606,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = ConversationProfilesClient.common_folder_path(**expected) @@ -2412,8 +2616,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "whelk" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationProfilesClient.common_organization_path(organization) assert expected == actual @@ -2421,7 +2624,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = ConversationProfilesClient.common_organization_path(**expected) @@ -2431,8 +2634,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "oyster" expected = "projects/{project}".format(project=project,) actual = ConversationProfilesClient.common_project_path(project) assert expected == actual @@ -2440,7 +2642,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = ConversationProfilesClient.common_project_path(**expected) @@ -2450,9 +2652,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2462,8 +2663,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = ConversationProfilesClient.common_location_path(**expected) @@ -2479,7 +2680,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationProfilesTransport, "_prep_wrapped_messages" ) as prep: client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2488,6 +2689,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationProfilesClient.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/dialogflow_v2/test_conversations.py b/tests/unit/gapic/dialogflow_v2/test_conversations.py index 2f3f7b185..bdd0dd7c8 100644 --- a/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2/test_conversations.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.dialogflow_v2.services.conversations import ConversationsAsyncClient from google.cloud.dialogflow_v2.services.conversations import ConversationsClient from google.cloud.dialogflow_v2.services.conversations import pagers from google.cloud.dialogflow_v2.services.conversations import transports +from google.cloud.dialogflow_v2.services.conversations.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.conversations.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation from google.cloud.dialogflow_v2.types import participant from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # 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(): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_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_conversations_client_from_service_account_info(client_class): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_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: @@ -161,7 +190,7 @@ def test_conversations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationsClient, "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() @@ -449,7 +478,7 @@ def test_create_conversation( transport: str = "grpc", request_type=gcd_conversation.CreateConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -467,28 +496,21 @@ def test_create_conversation( conversation_profile="conversation_profile_value", conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -503,7 +525,7 @@ def test_create_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -513,7 +535,6 @@ def test_create_conversation_empty_call(): client.create_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() @@ -523,7 +544,7 @@ async def test_create_conversation_async( request_type=gcd_conversation.CreateConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -543,27 +564,21 @@ async def test_create_conversation_async( conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -576,11 +591,12 @@ async def test_create_conversation_async_from_dict(): def test_create_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +604,6 @@ def test_create_conversation_field_headers(): type(client.transport.create_conversation), "__call__" ) as call: call.return_value = gcd_conversation.Conversation() - client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -603,11 +618,14 @@ def test_create_conversation_field_headers(): @pytest.mark.asyncio async def test_create_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -617,7 +635,6 @@ async def test_create_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation.Conversation() ) - await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -631,7 +648,7 @@ async def test_create_conversation_field_headers_async(): def test_create_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -639,7 +656,6 @@ def test_create_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation( @@ -651,14 +667,12 @@ def test_create_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") def test_create_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -672,7 +686,9 @@ def test_create_conversation_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -695,15 +711,15 @@ async def test_create_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") @pytest.mark.asyncio async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -719,7 +735,7 @@ def test_list_conversations( transport: str = "grpc", request_type=conversation.ListConversationsRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -734,19 +750,15 @@ def test_list_conversations( call.return_value = conversation.ListConversationsResponse( next_page_token="next_page_token_value", ) - response = client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == "next_page_token_value" @@ -758,7 +770,7 @@ def test_list_conversations_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -768,7 +780,6 @@ def test_list_conversations_empty_call(): client.list_conversations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() @@ -777,7 +788,7 @@ async def test_list_conversations_async( transport: str = "grpc_asyncio", request_type=conversation.ListConversationsRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -794,18 +805,15 @@ async def test_list_conversations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -815,11 +823,12 @@ async def test_list_conversations_async_from_dict(): def test_list_conversations_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -827,7 +836,6 @@ def test_list_conversations_field_headers(): type(client.transport.list_conversations), "__call__" ) as call: call.return_value = conversation.ListConversationsResponse() - client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -842,11 +850,14 @@ def test_list_conversations_field_headers(): @pytest.mark.asyncio async def test_list_conversations_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -856,7 +867,6 @@ async def test_list_conversations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListConversationsResponse() ) - await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -870,7 +880,7 @@ async def test_list_conversations_field_headers_async(): def test_list_conversations_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -878,7 +888,6 @@ def test_list_conversations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversations(parent="parent_value",) @@ -887,12 +896,11 @@ def test_list_conversations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversations_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -904,7 +912,9 @@ def test_list_conversations_flattened_error(): @pytest.mark.asyncio async def test_list_conversations_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -924,13 +934,14 @@ async def test_list_conversations_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_conversations_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -941,7 +952,7 @@ async def test_list_conversations_flattened_error_async(): def test_list_conversations_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -986,7 +997,7 @@ def test_list_conversations_pager(): def test_list_conversations_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1023,7 +1034,7 @@ def test_list_conversations_pages(): @pytest.mark.asyncio async def test_list_conversations_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1067,7 +1078,7 @@ async def test_list_conversations_async_pager(): @pytest.mark.asyncio async def test_list_conversations_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1110,7 +1121,7 @@ def test_get_conversation( transport: str = "grpc", request_type=conversation.GetConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1126,27 +1137,20 @@ def test_get_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1161,7 +1165,7 @@ def test_get_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1169,7 +1173,6 @@ def test_get_conversation_empty_call(): client.get_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() @@ -1178,7 +1181,7 @@ async def test_get_conversation_async( transport: str = "grpc_asyncio", request_type=conversation.GetConversationRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1196,26 +1199,20 @@ async def test_get_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1228,17 +1225,17 @@ async def test_get_conversation_async_from_dict(): def test_get_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: call.return_value = conversation.Conversation() - client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1253,11 +1250,14 @@ def test_get_conversation_field_headers(): @pytest.mark.asyncio async def test_get_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1265,7 +1265,6 @@ async def test_get_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1279,13 +1278,12 @@ async def test_get_conversation_field_headers_async(): def test_get_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation(name="name_value",) @@ -1294,12 +1292,11 @@ def test_get_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1311,7 +1308,9 @@ def test_get_conversation_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: @@ -1329,13 +1328,14 @@ async def test_get_conversation_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_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1349,7 +1349,7 @@ def test_complete_conversation( transport: str = "grpc", request_type=conversation.CompleteConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1367,27 +1367,20 @@ def test_complete_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1402,7 +1395,7 @@ def test_complete_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1412,7 +1405,6 @@ def test_complete_conversation_empty_call(): client.complete_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() @@ -1422,7 +1414,7 @@ async def test_complete_conversation_async( request_type=conversation.CompleteConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1442,26 +1434,20 @@ async def test_complete_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1474,11 +1460,12 @@ async def test_complete_conversation_async_from_dict(): def test_complete_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1486,7 +1473,6 @@ def test_complete_conversation_field_headers(): type(client.transport.complete_conversation), "__call__" ) as call: call.return_value = conversation.Conversation() - client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1501,11 +1487,14 @@ def test_complete_conversation_field_headers(): @pytest.mark.asyncio async def test_complete_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1515,7 +1504,6 @@ async def test_complete_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1529,7 +1517,7 @@ async def test_complete_conversation_field_headers_async(): def test_complete_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1537,7 +1525,6 @@ def test_complete_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.complete_conversation(name="name_value",) @@ -1546,12 +1533,11 @@ def test_complete_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_complete_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1563,7 +1549,9 @@ def test_complete_conversation_flattened_error(): @pytest.mark.asyncio async def test_complete_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1583,13 +1571,14 @@ async def test_complete_conversation_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_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1603,7 +1592,7 @@ def test_list_messages( transport: str = "grpc", request_type=conversation.ListMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1616,19 +1605,15 @@ def test_list_messages( call.return_value = conversation.ListMessagesResponse( next_page_token="next_page_token_value", ) - response = client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == "next_page_token_value" @@ -1640,7 +1625,7 @@ def test_list_messages_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1648,7 +1633,6 @@ def test_list_messages_empty_call(): client.list_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() @@ -1657,7 +1641,7 @@ async def test_list_messages_async( transport: str = "grpc_asyncio", request_type=conversation.ListMessagesRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1670,18 +1654,15 @@ async def test_list_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMessagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1691,17 +1672,17 @@ async def test_list_messages_async_from_dict(): def test_list_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: call.return_value = conversation.ListMessagesResponse() - client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1716,11 +1697,14 @@ def test_list_messages_field_headers(): @pytest.mark.asyncio async def test_list_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1728,7 +1712,6 @@ async def test_list_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse() ) - await client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1742,13 +1725,12 @@ async def test_list_messages_field_headers_async(): def test_list_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_messages(parent="parent_value",) @@ -1757,12 +1739,11 @@ def test_list_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1774,7 +1755,9 @@ def test_list_messages_flattened_error(): @pytest.mark.asyncio async def test_list_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1792,13 +1775,14 @@ async def test_list_messages_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_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1809,7 +1793,7 @@ async def test_list_messages_flattened_error_async(): def test_list_messages_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1847,7 +1831,7 @@ def test_list_messages_pager(): def test_list_messages_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -1877,7 +1861,7 @@ def test_list_messages_pages(): @pytest.mark.asyncio async def test_list_messages_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1914,7 +1898,7 @@ async def test_list_messages_async_pager(): @pytest.mark.asyncio async def test_list_messages_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1949,16 +1933,16 @@ async def test_list_messages_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( - 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.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -1968,7 +1952,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -1979,7 +1963,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationsClient(transport=transport) assert client.transport is transport @@ -1988,13 +1972,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2009,23 +1993,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 = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ConversationsGrpcTransport,) def test_conversations_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.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2037,7 +2021,7 @@ def test_conversations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2054,15 +2038,40 @@ def test_conversations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversations_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.dialogflow_v2.services.conversations.transports.ConversationsTransport._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.ConversationsTransport( + 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_conversations_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.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2078,19 +2087,36 @@ def test_conversations_base_transport_with_credentials_file(): def test_conversations_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.dialogflow_v2.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversations_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) + ConversationsClient() + 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_conversations_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) ConversationsClient() adc.assert_called_once_with( scopes=( @@ -2101,14 +2127,44 @@ def test_conversations_auth_adc(): ) -def test_conversations_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_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.ConversationsGrpcTransport( - 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.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_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", @@ -2118,6 +2174,121 @@ def test_conversations_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_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.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_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", + 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.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_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", + 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 +2297,7 @@ def test_conversations_transport_auth_adc(): ], ) def test_conversations_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 +2339,7 @@ def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_clas def test_conversations_host_no_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2178,7 +2349,7 @@ def test_conversations_host_no_port(): def test_conversations_host_with_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2232,9 +2403,9 @@ def test_conversations_transport_channel_mtls_with_client_cert_source(transport_ 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", @@ -2317,7 +2488,6 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): def test_conversation_path(): project = "squid" conversation = "clam" - expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, ) @@ -2340,7 +2510,6 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): project = "oyster" conversation_profile = "nudibranch" - expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2366,7 +2535,6 @@ def test_message_path(): project = "winkle" conversation = "nautilus" message = "scallop" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2389,7 +2557,6 @@ def test_parse_message_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2410,7 +2577,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) assert expected == actual @@ -2429,7 +2595,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) assert expected == actual @@ -2448,7 +2613,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) assert expected == actual @@ -2468,7 +2632,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2495,7 +2658,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationsTransport, "_prep_wrapped_messages" ) as prep: client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2504,6 +2667,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationsClient.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/dialogflow_v2/test_documents.py b/tests/unit/gapic/dialogflow_v2/test_documents.py index e61b3a1e7..8c7fd2b3c 100644 --- a/tests/unit/gapic/dialogflow_v2/test_documents.py +++ b/tests/unit/gapic/dialogflow_v2/test_documents.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.dialogflow_v2.services.documents import DocumentsAsyncClient from google.cloud.dialogflow_v2.services.documents import DocumentsClient from google.cloud.dialogflow_v2.services.documents import pagers from google.cloud.dialogflow_v2.services.documents import transports +from google.cloud.dialogflow_v2.services.documents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.documents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import document from google.cloud.dialogflow_v2.types import document as gcd_document 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 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 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(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_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_documents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_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: @@ -154,7 +183,7 @@ def test_documents_client_get_transport_class(): def test_documents_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(DocumentsClient, "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() @@ -438,7 +467,7 @@ def test_list_documents( transport: str = "grpc", request_type=document.ListDocumentsRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -451,19 +480,15 @@ def test_list_documents( call.return_value = document.ListDocumentsResponse( next_page_token="next_page_token_value", ) - response = client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == "next_page_token_value" @@ -475,7 +500,7 @@ def test_list_documents_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -483,7 +508,6 @@ def test_list_documents_empty_call(): client.list_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() @@ -492,7 +516,7 @@ async def test_list_documents_async( transport: str = "grpc_asyncio", request_type=document.ListDocumentsRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -505,18 +529,15 @@ async def test_list_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -526,17 +547,17 @@ async def test_list_documents_async_from_dict(): def test_list_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: call.return_value = document.ListDocumentsResponse() - client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -551,11 +572,12 @@ def test_list_documents_field_headers(): @pytest.mark.asyncio async def test_list_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -563,7 +585,6 @@ async def test_list_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse() ) - await client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -577,13 +598,12 @@ async def test_list_documents_field_headers_async(): def test_list_documents_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_documents(parent="parent_value",) @@ -592,12 +612,11 @@ def test_list_documents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_documents_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -609,7 +628,7 @@ def test_list_documents_flattened_error(): @pytest.mark.asyncio async def test_list_documents_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -627,13 +646,12 @@ async def test_list_documents_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_documents_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -644,7 +662,7 @@ async def test_list_documents_flattened_error_async(): def test_list_documents_pager(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -682,7 +700,7 @@ def test_list_documents_pager(): def test_list_documents_pages(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -712,7 +730,7 @@ def test_list_documents_pages(): @pytest.mark.asyncio async def test_list_documents_async_pager(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(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_documents_async_pager(): @pytest.mark.asyncio async def test_list_documents_async_pages(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -785,7 +803,7 @@ def test_get_document( transport: str = "grpc", request_type=document.GetDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -803,27 +821,19 @@ def test_get_document( enable_auto_reload=True, content_uri="content_uri_value", ) - response = client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -835,7 +845,7 @@ def test_get_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -843,7 +853,6 @@ def test_get_document_empty_call(): client.get_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() @@ -852,7 +861,7 @@ async def test_get_document_async( transport: str = "grpc_asyncio", request_type=document.GetDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -871,26 +880,19 @@ async def test_get_document_async( enable_auto_reload=True, ) ) - response = await client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -900,17 +902,17 @@ async def test_get_document_async_from_dict(): def test_get_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = document.Document() - client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -925,17 +927,17 @@ def test_get_document_field_headers(): @pytest.mark.asyncio async def test_get_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -949,13 +951,12 @@ async def test_get_document_field_headers_async(): def test_get_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_document(name="name_value",) @@ -964,12 +965,11 @@ def test_get_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -981,7 +981,7 @@ def test_get_document_flattened_error(): @pytest.mark.asyncio async def test_get_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: @@ -997,13 +997,12 @@ async def test_get_document_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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1017,7 +1016,7 @@ def test_create_document( transport: str = "grpc", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1028,13 +1027,11 @@ def test_create_document( with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1049,7 +1046,7 @@ def test_create_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1057,7 +1054,6 @@ def test_create_document_empty_call(): client.create_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() @@ -1066,7 +1062,7 @@ async def test_create_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1079,13 +1075,11 @@ async def test_create_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1098,17 +1092,17 @@ async def test_create_document_async_from_dict(): def test_create_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1123,11 +1117,12 @@ def test_create_document_field_headers(): @pytest.mark.asyncio async def test_create_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1135,7 +1130,6 @@ async def test_create_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1149,13 +1143,12 @@ async def test_create_document_field_headers_async(): def test_create_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__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_document( @@ -1166,14 +1159,12 @@ def test_create_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") def test_create_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1187,7 +1178,7 @@ def test_create_document_flattened_error(): @pytest.mark.asyncio async def test_create_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: @@ -1207,15 +1198,13 @@ async def test_create_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") @pytest.mark.asyncio async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1231,7 +1220,7 @@ def test_delete_document( transport: str = "grpc", request_type=document.DeleteDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,13 +1231,11 @@ def test_delete_document( with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1263,7 +1250,7 @@ def test_delete_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1271,7 +1258,6 @@ def test_delete_document_empty_call(): client.delete_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() @@ -1280,7 +1266,7 @@ async def test_delete_document_async( transport: str = "grpc_asyncio", request_type=document.DeleteDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1293,13 +1279,11 @@ async def test_delete_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1312,17 +1296,17 @@ async def test_delete_document_async_from_dict(): def test_delete_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1337,11 +1321,12 @@ def test_delete_document_field_headers(): @pytest.mark.asyncio async def test_delete_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1349,7 +1334,6 @@ async def test_delete_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1363,13 +1347,12 @@ async def test_delete_document_field_headers_async(): def test_delete_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__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.delete_document(name="name_value",) @@ -1378,12 +1361,11 @@ def test_delete_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1395,7 +1377,7 @@ def test_delete_document_flattened_error(): @pytest.mark.asyncio async def test_delete_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: @@ -1413,13 +1395,12 @@ async def test_delete_document_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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1433,7 +1414,7 @@ def test_update_document( transport: str = "grpc", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1444,13 +1425,11 @@ def test_update_document( with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1465,7 +1444,7 @@ def test_update_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1473,7 +1452,6 @@ def test_update_document_empty_call(): client.update_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() @@ -1482,7 +1460,7 @@ async def test_update_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1495,13 +1473,11 @@ async def test_update_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1514,17 +1490,17 @@ async def test_update_document_async_from_dict(): def test_update_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1541,11 +1517,12 @@ def test_update_document_field_headers(): @pytest.mark.asyncio async def test_update_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1553,7 +1530,6 @@ async def test_update_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1569,32 +1545,29 @@ async def test_update_document_field_headers_async(): def test_update_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__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.update_document( document=gcd_document.Document(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].document == gcd_document.Document(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_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1602,13 +1575,13 @@ def test_update_document_flattened_error(): client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(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_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: @@ -1622,22 +1595,20 @@ async def test_update_document_flattened_async(): # using the keyword arguments to the method. response = await client.update_document( document=gcd_document.Document(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].document == gcd_document.Document(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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1645,7 +1616,7 @@ async def test_update_document_flattened_error_async(): await client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1653,7 +1624,7 @@ def test_reload_document( transport: str = "grpc", request_type=document.ReloadDocumentRequest ): client = DocumentsClient( - 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 +1635,11 @@ def test_reload_document( with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1685,7 +1654,7 @@ def test_reload_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1662,6 @@ def test_reload_document_empty_call(): client.reload_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() @@ -1702,7 +1670,7 @@ async def test_reload_document_async( transport: str = "grpc_asyncio", request_type=document.ReloadDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1715,13 +1683,11 @@ async def test_reload_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1734,17 +1700,17 @@ async def test_reload_document_async_from_dict(): def test_reload_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1759,11 +1725,12 @@ def test_reload_document_field_headers(): @pytest.mark.asyncio async def test_reload_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1771,7 +1738,6 @@ async def test_reload_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1785,13 +1751,12 @@ async def test_reload_document_field_headers_async(): def test_reload_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__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.reload_document( @@ -1802,14 +1767,12 @@ def test_reload_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].content_uri == "content_uri_value" def test_reload_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1823,7 +1786,7 @@ def test_reload_document_flattened_error(): @pytest.mark.asyncio async def test_reload_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: @@ -1843,15 +1806,13 @@ async def test_reload_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].content_uri == "content_uri_value" @pytest.mark.asyncio async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1866,16 +1827,16 @@ async def test_reload_document_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( - 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.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -1885,7 +1846,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -1896,7 +1857,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DocumentsClient(transport=transport) assert client.transport is transport @@ -1905,13 +1866,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1923,23 +1884,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 = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DocumentsGrpcTransport,) def test_documents_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.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1951,7 +1912,7 @@ def test_documents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1974,15 +1935,40 @@ def test_documents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_documents_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.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentsTransport( + 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_documents_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.dialogflow_v2.services.documents.transports.DocumentsTransport._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.DocumentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1998,19 +1984,36 @@ def test_documents_base_transport_with_credentials_file(): def test_documents_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.dialogflow_v2.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_documents_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) + DocumentsClient() + 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_documents_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) DocumentsClient() adc.assert_called_once_with( scopes=( @@ -2021,14 +2024,38 @@ def test_documents_auth_adc(): ) -def test_documents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_documents_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.DocumentsGrpcTransport( - 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_documents_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", @@ -2038,12 +2065,123 @@ def test_documents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_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.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_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", + 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.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_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", + 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport], ) def test_documents_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: @@ -2085,7 +2223,7 @@ def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_documents_host_no_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2095,7 +2233,7 @@ def test_documents_host_no_port(): def test_documents_host_with_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2146,9 +2284,9 @@ def test_documents_transport_channel_mtls_with_client_cert_source(transport_clas 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", @@ -2227,7 +2365,7 @@ def test_documents_transport_channel_mtls_with_adc(transport_class): def test_documents_grpc_lro_client(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2240,7 +2378,7 @@ def test_documents_grpc_lro_client(): def test_documents_grpc_lro_async_client(): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2255,7 +2393,6 @@ def test_document_path(): project = "squid" knowledge_base = "clam" document = "whelk" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2278,7 +2415,6 @@ def test_parse_document_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2299,7 +2435,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = DocumentsClient.common_folder_path(folder) assert expected == actual @@ -2318,7 +2453,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = DocumentsClient.common_organization_path(organization) assert expected == actual @@ -2337,7 +2471,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = DocumentsClient.common_project_path(project) assert expected == actual @@ -2357,7 +2490,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, ) @@ -2384,7 +2516,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DocumentsTransport, "_prep_wrapped_messages" ) as prep: client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2393,6 +2525,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DocumentsClient.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/dialogflow_v2/test_entity_types.py b/tests/unit/gapic/dialogflow_v2/test_entity_types.py index a35603f06..81a4ae96f 100644 --- a/tests/unit/gapic/dialogflow_v2/test_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2/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,27 +23,57 @@ 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.dialogflow_v2.services.entity_types import EntityTypesAsyncClient from google.cloud.dialogflow_v2.services.entity_types import EntityTypesClient from google.cloud.dialogflow_v2.services.entity_types import pagers from google.cloud.dialogflow_v2.services.entity_types import transports +from google.cloud.dialogflow_v2.services.entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import entity_type as gcd_entity_type 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(): @@ -90,7 +119,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: @@ -105,7 +134,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: @@ -156,7 +185,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() @@ -440,7 +469,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, @@ -455,19 +484,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" @@ -479,7 +504,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. @@ -489,7 +514,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() @@ -498,7 +522,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, @@ -515,18 +539,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" @@ -536,11 +557,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. @@ -548,7 +570,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. @@ -563,11 +584,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. @@ -577,7 +599,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. @@ -591,7 +612,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( @@ -599,7 +620,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( @@ -610,14 +630,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -631,7 +649,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( @@ -653,15 +671,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -674,7 +690,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( @@ -716,7 +732,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( @@ -750,7 +766,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( @@ -791,7 +807,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( @@ -831,7 +847,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, @@ -848,30 +864,22 @@ def test_get_entity_type( auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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 @@ -883,7 +891,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. @@ -891,7 +899,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() @@ -900,7 +907,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, @@ -919,29 +926,22 @@ async def test_get_entity_type_async( enable_fuzzy_extraction=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 @@ -951,17 +951,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. @@ -976,11 +976,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. @@ -988,7 +989,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. @@ -1002,13 +1002,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( @@ -1019,14 +1018,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1040,7 +1037,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: @@ -1060,15 +1057,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1084,7 +1079,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcd_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, @@ -1103,30 +1098,22 @@ def test_create_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1138,7 +1125,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. @@ -1148,7 +1135,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() @@ -1158,7 +1144,7 @@ async def test_create_entity_type_async( request_type=gcd_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, @@ -1179,29 +1165,22 @@ async def test_create_entity_type_async( enable_fuzzy_extraction=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] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1211,11 +1190,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 = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1223,7 +1203,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1238,11 +1217,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 = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1252,7 +1232,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1266,7 +1245,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( @@ -1274,7 +1253,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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( @@ -1287,16 +1265,13 @@ 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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1311,7 +1286,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( @@ -1335,17 +1310,14 @@ 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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1362,7 +1334,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcd_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, @@ -1381,30 +1353,22 @@ def test_update_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1416,7 +1380,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. @@ -1426,7 +1390,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() @@ -1436,7 +1399,7 @@ async def test_update_entity_type_async( request_type=gcd_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, @@ -1457,29 +1420,22 @@ async def test_update_entity_type_async( enable_fuzzy_extraction=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] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1489,11 +1445,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 = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1501,7 +1458,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1518,11 +1474,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 = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,7 +1489,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1548,7 +1504,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( @@ -1556,7 +1512,6 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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( @@ -1568,14 +1523,12 @@ def test_update_entity_type_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1589,7 +1542,7 @@ def test_update_entity_type_flattened_error(): @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( @@ -1612,15 +1565,13 @@ async def test_update_entity_type_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].entity_type == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1636,7 +1587,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, @@ -1649,13 +1600,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. @@ -1670,7 +1619,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. @@ -1680,7 +1629,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() @@ -1689,7 +1637,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, @@ -1702,13 +1650,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. @@ -1721,11 +1667,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. @@ -1733,7 +1680,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. @@ -1748,11 +1694,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. @@ -1760,7 +1707,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. @@ -1774,7 +1720,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( @@ -1782,7 +1728,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",) @@ -1791,12 +1736,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. @@ -1808,7 +1752,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( @@ -1826,13 +1770,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. @@ -1846,7 +1789,7 @@ def test_batch_update_entity_types( transport: str = "grpc", request_type=entity_type.BatchUpdateEntityTypesRequest ): 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, @@ -1859,13 +1802,11 @@ def test_batch_update_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_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.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1880,7 +1821,7 @@ def test_batch_update_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. @@ -1890,7 +1831,6 @@ def test_batch_update_entity_types_empty_call(): client.batch_update_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() @@ -1900,7 +1840,7 @@ async def test_batch_update_entity_types_async( request_type=entity_type.BatchUpdateEntityTypesRequest, ): 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, @@ -1915,13 +1855,11 @@ async def test_batch_update_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_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.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1934,11 +1872,12 @@ async def test_batch_update_entity_types_async_from_dict(): def test_batch_update_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.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1946,7 +1885,6 @@ def test_batch_update_entity_types_field_headers(): type(client.transport.batch_update_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1961,11 +1899,12 @@ def test_batch_update_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_update_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.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1975,7 +1914,6 @@ async def test_batch_update_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1992,7 +1930,7 @@ def test_batch_delete_entity_types( transport: str = "grpc", request_type=entity_type.BatchDeleteEntityTypesRequest ): 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, @@ -2005,13 +1943,11 @@ def test_batch_delete_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_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.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2026,7 +1962,7 @@ def test_batch_delete_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. @@ -2036,7 +1972,6 @@ def test_batch_delete_entity_types_empty_call(): client.batch_delete_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() @@ -2046,7 +1981,7 @@ async def test_batch_delete_entity_types_async( request_type=entity_type.BatchDeleteEntityTypesRequest, ): 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, @@ -2061,13 +1996,11 @@ async def test_batch_delete_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_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.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2080,11 +2013,12 @@ async def test_batch_delete_entity_types_async_from_dict(): def test_batch_delete_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.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2092,7 +2026,6 @@ def test_batch_delete_entity_types_field_headers(): type(client.transport.batch_delete_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2107,11 +2040,12 @@ def test_batch_delete_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_delete_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.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2121,7 +2055,6 @@ async def test_batch_delete_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2135,7 +2068,7 @@ async def test_batch_delete_entity_types_field_headers_async(): def test_batch_delete_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( @@ -2143,7 +2076,6 @@ def test_batch_delete_entity_types_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.batch_delete_entity_types( @@ -2154,14 +2086,12 @@ def test_batch_delete_entity_types_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_names == ["entity_type_names_value"] def test_batch_delete_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. @@ -2175,7 +2105,7 @@ def test_batch_delete_entity_types_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_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( @@ -2197,15 +2127,13 @@ async def test_batch_delete_entity_types_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_names == ["entity_type_names_value"] @pytest.mark.asyncio async def test_batch_delete_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. @@ -2221,7 +2149,7 @@ def test_batch_create_entities( transport: str = "grpc", request_type=entity_type.BatchCreateEntitiesRequest ): 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, @@ -2234,13 +2162,11 @@ def test_batch_create_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_create_entities(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.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2255,7 +2181,7 @@ def test_batch_create_entities_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. @@ -2265,7 +2191,6 @@ def test_batch_create_entities_empty_call(): client.batch_create_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() @@ -2274,7 +2199,7 @@ async def test_batch_create_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchCreateEntitiesRequest ): 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, @@ -2289,13 +2214,11 @@ async def test_batch_create_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_create_entities(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.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2308,11 +2231,12 @@ async def test_batch_create_entities_async_from_dict(): def test_batch_create_entities_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.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2320,7 +2244,6 @@ def test_batch_create_entities_field_headers(): type(client.transport.batch_create_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2335,11 +2258,12 @@ def test_batch_create_entities_field_headers(): @pytest.mark.asyncio async def test_batch_create_entities_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.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2349,7 +2273,6 @@ async def test_batch_create_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2363,7 +2286,7 @@ async def test_batch_create_entities_field_headers_async(): def test_batch_create_entities_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( @@ -2371,7 +2294,6 @@ def test_batch_create_entities_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.batch_create_entities( @@ -2384,16 +2306,13 @@ def test_batch_create_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_create_entities_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. @@ -2408,7 +2327,7 @@ def test_batch_create_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_create_entities_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( @@ -2432,17 +2351,14 @@ async def test_batch_create_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_create_entities_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. @@ -2459,7 +2375,7 @@ def test_batch_update_entities( transport: str = "grpc", request_type=entity_type.BatchUpdateEntitiesRequest ): 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, @@ -2472,13 +2388,11 @@ def test_batch_update_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entities(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.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2493,7 +2407,7 @@ def test_batch_update_entities_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. @@ -2503,7 +2417,6 @@ def test_batch_update_entities_empty_call(): client.batch_update_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() @@ -2512,7 +2425,7 @@ async def test_batch_update_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchUpdateEntitiesRequest ): 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, @@ -2527,13 +2440,11 @@ async def test_batch_update_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entities(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.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2546,11 +2457,12 @@ async def test_batch_update_entities_async_from_dict(): def test_batch_update_entities_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.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2558,7 +2470,6 @@ def test_batch_update_entities_field_headers(): type(client.transport.batch_update_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2573,11 +2484,12 @@ def test_batch_update_entities_field_headers(): @pytest.mark.asyncio async def test_batch_update_entities_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.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2587,7 +2499,6 @@ async def test_batch_update_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2601,7 +2512,7 @@ async def test_batch_update_entities_field_headers_async(): def test_batch_update_entities_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( @@ -2609,7 +2520,6 @@ def test_batch_update_entities_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.batch_update_entities( @@ -2622,16 +2532,13 @@ def test_batch_update_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_update_entities_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. @@ -2646,7 +2553,7 @@ def test_batch_update_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_update_entities_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( @@ -2670,17 +2577,14 @@ async def test_batch_update_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_update_entities_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. @@ -2697,7 +2601,7 @@ def test_batch_delete_entities( transport: str = "grpc", request_type=entity_type.BatchDeleteEntitiesRequest ): 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, @@ -2710,13 +2614,11 @@ def test_batch_delete_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entities(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.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2731,7 +2633,7 @@ def test_batch_delete_entities_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. @@ -2741,7 +2643,6 @@ def test_batch_delete_entities_empty_call(): client.batch_delete_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() @@ -2750,7 +2651,7 @@ async def test_batch_delete_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchDeleteEntitiesRequest ): 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, @@ -2765,13 +2666,11 @@ async def test_batch_delete_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entities(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.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2784,11 +2683,12 @@ async def test_batch_delete_entities_async_from_dict(): def test_batch_delete_entities_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.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2796,7 +2696,6 @@ def test_batch_delete_entities_field_headers(): type(client.transport.batch_delete_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2811,11 +2710,12 @@ def test_batch_delete_entities_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entities_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.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2825,7 +2725,6 @@ async def test_batch_delete_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2839,7 +2738,7 @@ async def test_batch_delete_entities_field_headers_async(): def test_batch_delete_entities_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( @@ -2847,7 +2746,6 @@ def test_batch_delete_entities_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.batch_delete_entities( @@ -2860,16 +2758,13 @@ def test_batch_delete_entities_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_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" def test_batch_delete_entities_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. @@ -2884,7 +2779,7 @@ def test_batch_delete_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entities_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( @@ -2908,17 +2803,14 @@ async def test_batch_delete_entities_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_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_delete_entities_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. @@ -2934,16 +2826,16 @@ async def test_batch_delete_entities_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( @@ -2953,7 +2845,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( @@ -2964,7 +2856,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 @@ -2973,13 +2865,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 @@ -2991,23 +2883,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", ) @@ -3019,7 +2911,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 @@ -3046,15 +2938,40 @@ def test_entity_types_base_transport(): transport.operations_client +@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.dialogflow_v2.services.entity_types.transports.EntityTypesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EntityTypesTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=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.dialogflow_v2.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", ) @@ -3070,19 +2987,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.dialogflow_v2.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=( @@ -3093,14 +3027,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", @@ -3110,12 +3068,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", + 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", + 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: @@ -3157,7 +3230,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" ), @@ -3167,7 +3240,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" ), @@ -3218,9 +3291,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", @@ -3299,7 +3372,7 @@ def test_entity_types_transport_channel_mtls_with_adc(transport_class): def test_entity_types_grpc_lro_client(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3312,7 +3385,7 @@ def test_entity_types_grpc_lro_client(): def test_entity_types_grpc_lro_async_client(): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3326,7 +3399,6 @@ def test_entity_types_grpc_lro_async_client(): def test_entity_type_path(): project = "squid" entity_type = "clam" - expected = "projects/{project}/agent/entityTypes/{entity_type}".format( project=project, entity_type=entity_type, ) @@ -3348,7 +3420,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3369,7 +3440,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -3388,7 +3458,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -3407,7 +3476,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -3427,7 +3495,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, ) @@ -3454,7 +3521,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) @@ -3463,6 +3530,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/dialogflow_v2/test_environments.py b/tests/unit/gapic/dialogflow_v2/test_environments.py index df149b933..e2117f376 100644 --- a/tests/unit/gapic/dialogflow_v2/test_environments.py +++ b/tests/unit/gapic/dialogflow_v2/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,20 +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.dialogflow_v2.services.environments import EnvironmentsAsyncClient from google.cloud.dialogflow_v2.services.environments import EnvironmentsClient from google.cloud.dialogflow_v2.services.environments import pagers from google.cloud.dialogflow_v2.services.environments import transports +from google.cloud.dialogflow_v2.services.environments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.environments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import environment +from google.cloud.dialogflow_v2.types import fulfillment from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# 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(): @@ -83,7 +116,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: @@ -98,7 +131,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: @@ -149,7 +182,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() @@ -433,7 +466,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, @@ -448,19 +481,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" @@ -472,7 +501,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. @@ -482,7 +511,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -491,7 +519,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, @@ -508,18 +536,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" @@ -529,11 +554,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. @@ -541,7 +567,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. @@ -556,11 +581,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. @@ -570,7 +596,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. @@ -583,8 +608,76 @@ async def test_list_environments_field_headers_async(): assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] +def test_list_environments_flattened(): + 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.list_environments), "__call__" + ) 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",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +def test_list_environments_flattened_error(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_environments( + environment.ListEnvironmentsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_environments_flattened_async(): + 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.list_environments), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.ListEnvironmentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.ListEnvironmentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_environments(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_environments_flattened_error_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_environments( + environment.ListEnvironmentsRequest(), parent="parent_value", + ) + + 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( @@ -626,7 +719,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( @@ -660,7 +753,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( @@ -701,7 +794,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( @@ -737,180 +830,1291 @@ async def test_list_environments_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), +def test_get_environment( + transport: str = "grpc", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + response = client.get_environment(request) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + # 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.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=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: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_get_environment_async( + transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, 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_environment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) ) + 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() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Any value 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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) + # 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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # 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_environments_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - ) +@pytest.mark.asyncio +async def test_get_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("list_environments",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # Any value 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" -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" - ) as load_creds, mock.patch( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() ) + 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] == request -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( - "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() + # 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_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) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id=None, - ) +def test_create_environment( + transport: str = "grpc", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_environments_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" - ) - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + 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] == environment.CreateEnvironmentRequest() -@pytest.mark.parametrize( - "transport_class", - [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], -) -def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED - # Check ssl_channel_credentials is used if provided. + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async( + transport: str = "grpc_asyncio", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + 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] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + 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] == 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_update_environment( + transport: str = "grpc", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + 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] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async( + transport: str = "grpc_asyncio", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + 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] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +def test_delete_environment( + transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) 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. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async( + transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) 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. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + 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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + 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. + 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_environment_history( + transport: str = "grpc", request_type=environment.GetEnvironmentHistoryRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + response = client.get_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.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_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=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_environment_history), "__call__" + ) as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async( + transport: str = "grpc_asyncio", + request_type=environment.GetEnvironmentHistoryRequest, +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + ) + response = await client.get_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.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = environment.EnvironmentHistory() + client.get_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] == 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_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory() + ) + await client.get_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] == 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_get_environment_history_pager(): + 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_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) for i in results) + + +def test_get_environment_history_pages(): + 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_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + 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_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, environment.EnvironmentHistory.Entry) for i in responses + ) + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + 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_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_environments", + "get_environment", + "create_environment", + "update_environment", + "delete_environment", + "get_environment_history", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@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( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.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.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = 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(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@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(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", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@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", + 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", + 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 = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: mock_ssl_channel_creds = mock.Mock() transport_class( @@ -950,7 +2154,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" ), @@ -960,7 +2164,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" ), @@ -1011,9 +2215,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", @@ -1093,7 +2297,6 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environment_path(): project = "squid" environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format( project=project, environment=environment, ) @@ -1113,9 +2316,26 @@ def test_parse_environment_path(): assert expected == actual -def test_common_billing_account_path(): - billing_account = "oyster" +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1125,7 +2345,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -1135,8 +2355,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -1144,7 +2363,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = EnvironmentsClient.common_folder_path(**expected) @@ -1154,8 +2373,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -1163,7 +2381,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = EnvironmentsClient.common_organization_path(**expected) @@ -1173,8 +2391,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -1182,7 +2399,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = EnvironmentsClient.common_project_path(**expected) @@ -1192,9 +2409,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1204,8 +2420,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = EnvironmentsClient.common_location_path(**expected) @@ -1221,7 +2437,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) @@ -1230,6 +2446,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/dialogflow_v2/test_fulfillments.py b/tests/unit/gapic/dialogflow_v2/test_fulfillments.py new file mode 100644 index 000000000..6cd7f86a8 --- /dev/null +++ b/tests/unit/gapic/dialogflow_v2/test_fulfillments.py @@ -0,0 +1,1586 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsAsyncClient +from google.cloud.dialogflow_v2.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2.services.fulfillments import transports +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.fulfillments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2.types import fulfillment +from google.cloud.dialogflow_v2.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +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(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) +def test_fulfillments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) +def test_fulfillments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +def test_fulfillments_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(FulfillmentsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FulfillmentsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_get_fulfillment( + transport: str = "grpc", request_type=fulfillment.GetFulfillmentRequest +): + client = FulfillmentsClient( + 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_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name="name_value", + display_name="display_name_value", + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_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 = FulfillmentsClient( + 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_fulfillment), "__call__") as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async( + transport: str = "grpc_asyncio", request_type=fulfillment.GetFulfillmentRequest +): + client = FulfillmentsAsyncClient( + 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_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment( + name="name_value", display_name="display_name_value", enabled=True, + ) + ) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(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_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment() + ) + await client.get_fulfillment(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_fulfillment_flattened(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment(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_fulfillment_flattened_error(): + client = FulfillmentsClient(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_fulfillment( + fulfillment.GetFulfillmentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment(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_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient(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_fulfillment( + fulfillment.GetFulfillmentRequest(), name="name_value", + ) + + +def test_update_fulfillment( + transport: str = "grpc", request_type=gcd_fulfillment.UpdateFulfillmentRequest +): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name="name_value", + display_name="display_name_value", + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_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 = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async( + transport: str = "grpc_asyncio", + request_type=gcd_fulfillment.UpdateFulfillmentRequest, +): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment( + name="name_value", display_name="display_name_value", enabled=True, + ) + ) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = "fulfillment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(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", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = "fulfillment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment() + ) + await client.update_fulfillment(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", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.FulfillmentsGrpcTransport,) + + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_fulfillment", + "update_fulfillment", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + 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_fulfillments_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.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_fulfillments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + 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_fulfillments_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) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_fulfillments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_fulfillments_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.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_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", + 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.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_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", + 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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder,) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization,) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project,) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2/test_intents.py b/tests/unit/gapic/dialogflow_v2/test_intents.py index 0cbed51cb..ae1ba6aae 100644 --- a/tests/unit/gapic/dialogflow_v2/test_intents.py +++ b/tests/unit/gapic/dialogflow_v2/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,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.dialogflow_v2.services.intents import IntentsAsyncClient from google.cloud.dialogflow_v2.services.intents import IntentsClient from google.cloud.dialogflow_v2.services.intents import pagers from google.cloud.dialogflow_v2.services.intents import transports +from google.cloud.dialogflow_v2.services.intents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.intents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import intent from google.cloud.dialogflow_v2.types import intent as gcd_intent 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", [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: @@ -103,7 +132,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: @@ -146,7 +175,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() @@ -418,7 +447,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, @@ -431,19 +460,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" @@ -455,7 +480,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. @@ -463,7 +488,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -472,7 +496,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, @@ -485,18 +509,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" @@ -506,17 +527,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. @@ -531,11 +552,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. @@ -543,7 +565,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. @@ -557,13 +578,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( @@ -574,14 +594,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -595,7 +613,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: @@ -615,15 +633,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -636,7 +652,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: @@ -668,7 +684,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: @@ -692,7 +708,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( @@ -723,7 +739,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( @@ -751,7 +767,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, @@ -778,49 +794,31 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -832,7 +830,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. @@ -840,7 +838,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -849,7 +846,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, @@ -878,48 +875,31 @@ async def test_get_intent_async( parent_followup_intent_name="parent_followup_intent_name_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.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -929,17 +909,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. @@ -954,17 +934,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. @@ -978,13 +958,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( @@ -995,14 +974,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1016,7 +993,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: @@ -1034,15 +1011,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1058,7 +1033,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcd_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, @@ -1085,51 +1060,33 @@ def test_create_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1141,7 +1098,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. @@ -1149,7 +1106,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() @@ -1158,7 +1114,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -1189,50 +1145,33 @@ async def test_create_intent_async( parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1242,17 +1181,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 = gcd_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 = gcd_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1267,17 +1206,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 = gcd_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(gcd_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1291,13 +1230,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 = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1310,16 +1248,13 @@ 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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1334,7 +1269,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: @@ -1354,17 +1289,14 @@ 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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1381,7 +1313,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcd_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, @@ -1408,51 +1340,33 @@ def test_update_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1464,7 +1378,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. @@ -1472,7 +1386,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() @@ -1481,7 +1394,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -1512,50 +1425,33 @@ async def test_update_intent_async( parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1565,17 +1461,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 = gcd_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 = gcd_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1590,17 +1486,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 = gcd_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(gcd_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1614,35 +1510,31 @@ 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 = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcd_intent.Intent(name="name_value"), language_code="language_code_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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1651,13 +1543,13 @@ def test_update_intent_flattened_error(): gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), language_code="language_code_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: @@ -1670,24 +1562,21 @@ async def test_update_intent_flattened_async(): response = await client.update_intent( intent=gcd_intent.Intent(name="name_value"), language_code="language_code_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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1696,7 +1585,7 @@ async def test_update_intent_flattened_error_async(): gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1704,7 +1593,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, @@ -1715,13 +1604,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. @@ -1736,7 +1623,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. @@ -1744,7 +1631,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1753,7 +1639,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, @@ -1764,13 +1650,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. @@ -1783,17 +1667,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. @@ -1808,17 +1692,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. @@ -1832,13 +1716,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",) @@ -1847,12 +1730,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. @@ -1864,7 +1746,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: @@ -1880,13 +1762,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. @@ -1900,7 +1781,7 @@ def test_batch_update_intents( transport: str = "grpc", request_type=intent.BatchUpdateIntentsRequest ): 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, @@ -1913,13 +1794,11 @@ def test_batch_update_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_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.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1934,7 +1813,7 @@ def test_batch_update_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. @@ -1944,7 +1823,6 @@ def test_batch_update_intents_empty_call(): client.batch_update_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() @@ -1953,7 +1831,7 @@ async def test_batch_update_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchUpdateIntentsRequest ): 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, @@ -1968,13 +1846,11 @@ async def test_batch_update_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_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.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1987,11 +1863,12 @@ async def test_batch_update_intents_async_from_dict(): def test_batch_update_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.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1999,7 +1876,6 @@ def test_batch_update_intents_field_headers(): type(client.transport.batch_update_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2014,11 +1890,12 @@ def test_batch_update_intents_field_headers(): @pytest.mark.asyncio async def test_batch_update_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.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2028,7 +1905,6 @@ async def test_batch_update_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2042,7 +1918,7 @@ async def test_batch_update_intents_field_headers_async(): def test_batch_update_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( @@ -2050,7 +1926,6 @@ def test_batch_update_intents_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.batch_update_intents( @@ -2065,16 +1940,14 @@ def test_batch_update_intents_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_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) def test_batch_update_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. @@ -2091,7 +1964,7 @@ def test_batch_update_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_update_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( @@ -2117,9 +1990,7 @@ async def test_batch_update_intents_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_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) @@ -2127,7 +1998,7 @@ async def test_batch_update_intents_flattened_async(): @pytest.mark.asyncio async def test_batch_update_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. @@ -2146,7 +2017,7 @@ def test_batch_delete_intents( transport: str = "grpc", request_type=intent.BatchDeleteIntentsRequest ): 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, @@ -2159,13 +2030,11 @@ def test_batch_delete_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_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.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2180,7 +2049,7 @@ def test_batch_delete_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. @@ -2190,7 +2059,6 @@ def test_batch_delete_intents_empty_call(): client.batch_delete_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() @@ -2199,7 +2067,7 @@ async def test_batch_delete_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchDeleteIntentsRequest ): 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, @@ -2214,13 +2082,11 @@ async def test_batch_delete_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_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.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2233,11 +2099,12 @@ async def test_batch_delete_intents_async_from_dict(): def test_batch_delete_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.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2245,7 +2112,6 @@ def test_batch_delete_intents_field_headers(): type(client.transport.batch_delete_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2260,11 +2126,12 @@ def test_batch_delete_intents_field_headers(): @pytest.mark.asyncio async def test_batch_delete_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.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2274,7 +2141,6 @@ async def test_batch_delete_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2288,7 +2154,7 @@ async def test_batch_delete_intents_field_headers_async(): def test_batch_delete_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( @@ -2296,7 +2162,6 @@ def test_batch_delete_intents_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.batch_delete_intents( @@ -2307,14 +2172,12 @@ def test_batch_delete_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] def test_batch_delete_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. @@ -2328,7 +2191,7 @@ def test_batch_delete_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_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( @@ -2350,15 +2213,13 @@ async def test_batch_delete_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] @pytest.mark.asyncio async def test_batch_delete_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. @@ -2373,16 +2234,16 @@ async def test_batch_delete_intents_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( @@ -2392,7 +2253,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( @@ -2403,7 +2264,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 @@ -2412,13 +2273,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 @@ -2430,23 +2291,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", ) @@ -2458,7 +2319,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 @@ -2482,15 +2343,40 @@ def test_intents_base_transport(): transport.operations_client +@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.dialogflow_v2.services.intents.transports.IntentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.IntentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=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.dialogflow_v2.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", ) @@ -2506,19 +2392,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.dialogflow_v2.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=( @@ -2529,14 +2432,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", @@ -2546,12 +2473,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", + 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", + 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: @@ -2593,7 +2631,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" ), @@ -2603,7 +2641,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" ), @@ -2654,9 +2692,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", @@ -2735,7 +2773,7 @@ def test_intents_transport_channel_mtls_with_adc(transport_class): def test_intents_grpc_lro_client(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2748,7 +2786,7 @@ def test_intents_grpc_lro_client(): def test_intents_grpc_lro_async_client(): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2763,7 +2801,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2787,7 +2824,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2809,7 +2845,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2830,7 +2865,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2849,7 +2883,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2868,7 +2901,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2888,7 +2920,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, ) @@ -2915,7 +2946,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) @@ -2924,6 +2955,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/dialogflow_v2/test_knowledge_bases.py b/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py index d20501047..5c9bf24ca 100644 --- a/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.py +++ b/tests/unit/gapic/dialogflow_v2/test_knowledge_bases.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.dialogflow_v2.services.knowledge_bases import ( KnowledgeBasesAsyncClient, @@ -38,10 +37,40 @@ from google.cloud.dialogflow_v2.services.knowledge_bases import KnowledgeBasesClient from google.cloud.dialogflow_v2.services.knowledge_bases import pagers from google.cloud.dialogflow_v2.services.knowledge_bases import transports +from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.knowledge_bases.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import knowledge_base from google.cloud.dialogflow_v2.types import knowledge_base as gcd_knowledge_base 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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_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: @@ -109,7 +138,7 @@ def test_knowledge_bases_client_from_service_account_info(client_class): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_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: @@ -162,7 +191,7 @@ def test_knowledge_bases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(KnowledgeBasesClient, "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() @@ -450,7 +479,7 @@ def test_list_knowledge_bases( transport: str = "grpc", request_type=knowledge_base.ListKnowledgeBasesRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,19 +494,15 @@ def test_list_knowledge_bases( call.return_value = knowledge_base.ListKnowledgeBasesResponse( next_page_token="next_page_token_value", ) - response = client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == "next_page_token_value" @@ -489,7 +514,7 @@ def test_list_knowledge_bases_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -499,7 +524,6 @@ def test_list_knowledge_bases_empty_call(): client.list_knowledge_bases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() @@ -509,7 +533,7 @@ async def test_list_knowledge_bases_async( request_type=knowledge_base.ListKnowledgeBasesRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,18 +550,15 @@ async def test_list_knowledge_bases_async( next_page_token="next_page_token_value", ) ) - response = await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -547,11 +568,12 @@ async def test_list_knowledge_bases_async_from_dict(): def test_list_knowledge_bases_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -559,7 +581,6 @@ def test_list_knowledge_bases_field_headers(): type(client.transport.list_knowledge_bases), "__call__" ) as call: call.return_value = knowledge_base.ListKnowledgeBasesResponse() - client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -574,11 +595,14 @@ def test_list_knowledge_bases_field_headers(): @pytest.mark.asyncio async def test_list_knowledge_bases_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -588,7 +612,6 @@ async def test_list_knowledge_bases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.ListKnowledgeBasesResponse() ) - await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -602,7 +625,7 @@ async def test_list_knowledge_bases_field_headers_async(): def test_list_knowledge_bases_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -610,7 +633,6 @@ def test_list_knowledge_bases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.ListKnowledgeBasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_knowledge_bases(parent="parent_value",) @@ -619,12 +641,11 @@ def test_list_knowledge_bases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -636,7 +657,9 @@ def test_list_knowledge_bases_flattened_error(): @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -656,13 +679,14 @@ async def test_list_knowledge_bases_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_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -673,7 +697,7 @@ async def test_list_knowledge_bases_flattened_error_async(): def test_list_knowledge_bases_pager(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -719,7 +743,7 @@ def test_list_knowledge_bases_pager(): def test_list_knowledge_bases_pages(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -757,7 +781,7 @@ def test_list_knowledge_bases_pages(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -802,7 +826,7 @@ async def test_list_knowledge_bases_async_pager(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -846,7 +870,7 @@ def test_get_knowledge_base( transport: str = "grpc", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -863,23 +887,17 @@ def test_get_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -891,7 +909,7 @@ def test_get_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -901,7 +919,6 @@ def test_get_knowledge_base_empty_call(): client.get_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() @@ -910,7 +927,7 @@ async def test_get_knowledge_base_async( transport: str = "grpc_asyncio", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -929,22 +946,17 @@ async def test_get_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -954,11 +966,12 @@ async def test_get_knowledge_base_async_from_dict(): def test_get_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -966,7 +979,6 @@ def test_get_knowledge_base_field_headers(): type(client.transport.get_knowledge_base), "__call__" ) as call: call.return_value = knowledge_base.KnowledgeBase() - client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -981,11 +993,14 @@ def test_get_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_get_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -995,7 +1010,6 @@ async def test_get_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.KnowledgeBase() ) - await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1009,7 +1023,7 @@ async def test_get_knowledge_base_field_headers_async(): def test_get_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1017,7 +1031,6 @@ def test_get_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_knowledge_base(name="name_value",) @@ -1026,12 +1039,11 @@ def test_get_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1043,7 +1055,9 @@ def test_get_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1063,13 +1077,14 @@ async def test_get_knowledge_base_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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1083,7 +1098,7 @@ def test_create_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,23 +1115,17 @@ def test_create_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1128,7 +1137,7 @@ def test_create_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1138,7 +1147,6 @@ def test_create_knowledge_base_empty_call(): client.create_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() @@ -1148,7 +1156,7 @@ async def test_create_knowledge_base_async( request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1167,22 +1175,17 @@ async def test_create_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1192,11 +1195,12 @@ async def test_create_knowledge_base_async_from_dict(): def test_create_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1204,7 +1208,6 @@ def test_create_knowledge_base_field_headers(): type(client.transport.create_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1219,11 +1222,14 @@ def test_create_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_create_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1233,7 +1239,6 @@ async def test_create_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1247,7 +1252,7 @@ async def test_create_knowledge_base_field_headers_async(): def test_create_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1255,7 +1260,6 @@ def test_create_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_knowledge_base( @@ -1267,16 +1271,14 @@ def test_create_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1290,7 +1292,9 @@ def test_create_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,9 +1317,7 @@ async def test_create_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) @@ -1323,7 +1325,9 @@ async def test_create_knowledge_base_flattened_async(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1339,7 +1343,7 @@ def test_delete_knowledge_base( transport: str = "grpc", request_type=knowledge_base.DeleteKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1352,13 +1356,11 @@ def test_delete_knowledge_base( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1373,7 +1375,7 @@ def test_delete_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1383,7 +1385,6 @@ def test_delete_knowledge_base_empty_call(): client.delete_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() @@ -1393,7 +1394,7 @@ async def test_delete_knowledge_base_async( request_type=knowledge_base.DeleteKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1406,13 +1407,11 @@ async def test_delete_knowledge_base_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1425,11 +1424,12 @@ async def test_delete_knowledge_base_async_from_dict(): def test_delete_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1437,7 +1437,6 @@ def test_delete_knowledge_base_field_headers(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = None - client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1452,11 +1451,14 @@ def test_delete_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_delete_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1464,7 +1466,6 @@ async def test_delete_knowledge_base_field_headers_async(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1478,7 +1479,7 @@ async def test_delete_knowledge_base_field_headers_async(): def test_delete_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1486,7 +1487,6 @@ def test_delete_knowledge_base_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_knowledge_base(name="name_value",) @@ -1495,12 +1495,11 @@ def test_delete_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1512,7 +1511,9 @@ def test_delete_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1530,13 +1531,14 @@ async def test_delete_knowledge_base_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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1550,7 +1552,7 @@ def test_update_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1567,23 +1569,17 @@ def test_update_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1595,7 +1591,7 @@ def test_update_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1605,7 +1601,6 @@ def test_update_knowledge_base_empty_call(): client.update_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() @@ -1615,7 +1610,7 @@ async def test_update_knowledge_base_async( request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1634,22 +1629,17 @@ async def test_update_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1659,11 +1649,12 @@ async def test_update_knowledge_base_async_from_dict(): def test_update_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1671,7 +1662,6 @@ def test_update_knowledge_base_field_headers(): type(client.transport.update_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1689,11 +1679,14 @@ def test_update_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_update_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1703,7 +1696,6 @@ async def test_update_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1720,7 +1712,7 @@ async def test_update_knowledge_base_field_headers_async(): def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1728,28 +1720,25 @@ def test_update_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(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].knowledge_base == gcd_knowledge_base.KnowledgeBase( 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_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1757,13 +1746,15 @@ def test_update_knowledge_base_flattened_error(): client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(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_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1779,24 +1770,24 @@ async def test_update_knowledge_base_flattened_async(): # using the keyword arguments to the method. response = await client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(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].knowledge_base == gcd_knowledge_base.KnowledgeBase( 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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1804,23 +1795,23 @@ async def test_update_knowledge_base_flattened_error_async(): await client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( - 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.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1830,7 +1821,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1841,7 +1832,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = KnowledgeBasesClient(transport=transport) assert client.transport is transport @@ -1850,13 +1841,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1871,23 +1862,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 = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.KnowledgeBasesGrpcTransport,) def test_knowledge_bases_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.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1899,7 +1890,7 @@ def test_knowledge_bases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1916,15 +1907,40 @@ def test_knowledge_bases_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_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.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + 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_knowledge_bases_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.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._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.KnowledgeBasesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1940,19 +1956,36 @@ def test_knowledge_bases_base_transport_with_credentials_file(): def test_knowledge_bases_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.dialogflow_v2.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_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) + KnowledgeBasesClient() + 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_knowledge_bases_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) KnowledgeBasesClient() adc.assert_called_once_with( scopes=( @@ -1963,14 +1996,44 @@ def test_knowledge_bases_auth_adc(): ) -def test_knowledge_bases_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport( - 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.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_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", @@ -1980,6 +2043,121 @@ def test_knowledge_bases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_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", + 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.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_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", + 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", [ @@ -1988,7 +2166,7 @@ def test_knowledge_bases_transport_auth_adc(): ], ) def test_knowledge_bases_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: @@ -2030,7 +2208,7 @@ def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_cl def test_knowledge_bases_host_no_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2040,7 +2218,7 @@ def test_knowledge_bases_host_no_port(): def test_knowledge_bases_host_with_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2096,9 +2274,9 @@ def test_knowledge_bases_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", @@ -2181,7 +2359,6 @@ def test_knowledge_bases_transport_channel_mtls_with_adc(transport_class): def test_knowledge_base_path(): project = "squid" knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2203,7 +2380,6 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2224,7 +2400,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = KnowledgeBasesClient.common_folder_path(folder) assert expected == actual @@ -2243,7 +2418,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = KnowledgeBasesClient.common_organization_path(organization) assert expected == actual @@ -2262,7 +2436,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = KnowledgeBasesClient.common_project_path(project) assert expected == actual @@ -2282,7 +2455,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, ) @@ -2309,7 +2481,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.KnowledgeBasesTransport, "_prep_wrapped_messages" ) as prep: client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2318,6 +2490,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = KnowledgeBasesClient.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/dialogflow_v2/test_participants.py b/tests/unit/gapic/dialogflow_v2/test_participants.py index bef06db64..29f9b6b0f 100644 --- a/tests/unit/gapic/dialogflow_v2/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2/test_participants.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,18 +23,24 @@ 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.dialogflow_v2.services.participants import ParticipantsAsyncClient from google.cloud.dialogflow_v2.services.participants import ParticipantsClient from google.cloud.dialogflow_v2.services.participants import pagers from google.cloud.dialogflow_v2.services.participants import transports +from google.cloud.dialogflow_v2.services.participants.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.participants.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import entity_type @@ -44,9 +49,33 @@ from google.cloud.dialogflow_v2.types import session from google.cloud.dialogflow_v2.types import 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 struct_pb2 as struct # type: ignore -from google.type import latlng_pb2 as latlng # type: ignore +from google.protobuf import field_mask_pb2 # 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(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_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_participants_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_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: @@ -158,7 +187,7 @@ def test_participants_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ParticipantsClient, "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() @@ -442,7 +471,7 @@ def test_create_participant( transport: str = "grpc", request_type=gcd_participant.CreateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -459,23 +488,17 @@ def test_create_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -487,7 +510,7 @@ def test_create_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -497,7 +520,6 @@ def test_create_participant_empty_call(): client.create_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() @@ -507,7 +529,7 @@ async def test_create_participant_async( request_type=gcd_participant.CreateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -526,22 +548,17 @@ async def test_create_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -551,11 +568,12 @@ async def test_create_participant_async_from_dict(): def test_create_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -563,7 +581,6 @@ def test_create_participant_field_headers(): type(client.transport.create_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -578,11 +595,12 @@ def test_create_participant_field_headers(): @pytest.mark.asyncio async def test_create_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -592,7 +610,6 @@ async def test_create_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -606,7 +623,7 @@ async def test_create_participant_field_headers_async(): def test_create_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -614,7 +631,6 @@ def test_create_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_participant( @@ -626,14 +642,12 @@ def test_create_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") def test_create_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -647,7 +661,7 @@ def test_create_participant_flattened_error(): @pytest.mark.asyncio async def test_create_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -670,15 +684,13 @@ async def test_create_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") @pytest.mark.asyncio async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -694,7 +706,7 @@ def test_get_participant( transport: str = "grpc", request_type=participant.GetParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -709,23 +721,17 @@ def test_get_participant( role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -737,7 +743,7 @@ def test_get_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -745,7 +751,6 @@ def test_get_participant_empty_call(): client.get_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() @@ -754,7 +759,7 @@ async def test_get_participant_async( transport: str = "grpc_asyncio", request_type=participant.GetParticipantRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -771,22 +776,17 @@ async def test_get_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -796,17 +796,17 @@ async def test_get_participant_async_from_dict(): def test_get_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: call.return_value = participant.Participant() - client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -821,11 +821,12 @@ def test_get_participant_field_headers(): @pytest.mark.asyncio async def test_get_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -833,7 +834,6 @@ async def test_get_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.Participant() ) - await client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -847,13 +847,12 @@ async def test_get_participant_field_headers_async(): def test_get_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_participant(name="name_value",) @@ -862,12 +861,11 @@ def test_get_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -879,7 +877,7 @@ def test_get_participant_flattened_error(): @pytest.mark.asyncio async def test_get_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: @@ -897,13 +895,12 @@ async def test_get_participant_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_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -917,7 +914,7 @@ def test_list_participants( transport: str = "grpc", request_type=participant.ListParticipantsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -932,19 +929,15 @@ def test_list_participants( call.return_value = participant.ListParticipantsResponse( next_page_token="next_page_token_value", ) - response = client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == "next_page_token_value" @@ -956,7 +949,7 @@ def test_list_participants_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -966,7 +959,6 @@ def test_list_participants_empty_call(): client.list_participants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() @@ -975,7 +967,7 @@ async def test_list_participants_async( transport: str = "grpc_asyncio", request_type=participant.ListParticipantsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -992,18 +984,15 @@ async def test_list_participants_async( next_page_token="next_page_token_value", ) ) - response = await client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListParticipantsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1013,11 +1002,12 @@ async def test_list_participants_async_from_dict(): def test_list_participants_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1025,7 +1015,6 @@ def test_list_participants_field_headers(): type(client.transport.list_participants), "__call__" ) as call: call.return_value = participant.ListParticipantsResponse() - client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1040,11 +1029,12 @@ def test_list_participants_field_headers(): @pytest.mark.asyncio async def test_list_participants_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1054,7 +1044,6 @@ async def test_list_participants_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListParticipantsResponse() ) - await client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1068,7 +1057,7 @@ async def test_list_participants_field_headers_async(): def test_list_participants_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1076,7 +1065,6 @@ def test_list_participants_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.ListParticipantsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_participants(parent="parent_value",) @@ -1085,12 +1073,11 @@ def test_list_participants_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_participants_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1102,7 +1089,7 @@ def test_list_participants_flattened_error(): @pytest.mark.asyncio async def test_list_participants_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1122,13 +1109,12 @@ async def test_list_participants_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_participants_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1139,7 +1125,7 @@ async def test_list_participants_flattened_error_async(): def test_list_participants_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1181,7 +1167,7 @@ def test_list_participants_pager(): def test_list_participants_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1215,7 +1201,7 @@ def test_list_participants_pages(): @pytest.mark.asyncio async def test_list_participants_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1256,7 +1242,7 @@ async def test_list_participants_async_pager(): @pytest.mark.asyncio async def test_list_participants_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1296,7 +1282,7 @@ def test_update_participant( transport: str = "grpc", request_type=gcd_participant.UpdateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1313,23 +1299,17 @@ def test_update_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", ) - response = client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -1341,7 +1321,7 @@ def test_update_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1351,7 +1331,6 @@ def test_update_participant_empty_call(): client.update_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() @@ -1361,7 +1340,7 @@ async def test_update_participant_async( request_type=gcd_participant.UpdateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1380,22 +1359,17 @@ async def test_update_participant_async( sip_recording_media_label="sip_recording_media_label_value", ) ) - response = await client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.sip_recording_media_label == "sip_recording_media_label_value" @@ -1405,11 +1379,12 @@ async def test_update_participant_async_from_dict(): def test_update_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1417,7 +1392,6 @@ def test_update_participant_field_headers(): type(client.transport.update_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1434,11 +1408,12 @@ def test_update_participant_field_headers(): @pytest.mark.asyncio async def test_update_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1448,7 +1423,6 @@ async def test_update_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1464,7 +1438,7 @@ async def test_update_participant_field_headers_async(): def test_update_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1472,26 +1446,23 @@ def test_update_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_participant( participant=gcd_participant.Participant(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].participant == gcd_participant.Participant(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_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1499,13 +1470,13 @@ def test_update_participant_flattened_error(): client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(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_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1521,22 +1492,20 @@ async def test_update_participant_flattened_async(): # using the keyword arguments to the method. response = await client.update_participant( participant=gcd_participant.Participant(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].participant == gcd_participant.Participant(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_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1544,7 +1513,7 @@ async def test_update_participant_flattened_error_async(): await client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1552,7 +1521,7 @@ def test_analyze_content( transport: str = "grpc", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1565,19 +1534,15 @@ def test_analyze_content( call.return_value = gcd_participant.AnalyzeContentResponse( reply_text="reply_text_value", ) - response = client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1589,7 +1554,7 @@ def test_analyze_content_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1597,7 +1562,6 @@ def test_analyze_content_empty_call(): client.analyze_content() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() @@ -1606,7 +1570,7 @@ async def test_analyze_content_async( transport: str = "grpc_asyncio", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1619,18 +1583,15 @@ async def test_analyze_content_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse(reply_text="reply_text_value",) ) - response = await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1640,17 +1601,17 @@ async def test_analyze_content_async_from_dict(): def test_analyze_content_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: call.return_value = gcd_participant.AnalyzeContentResponse() - client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1665,11 +1626,12 @@ def test_analyze_content_field_headers(): @pytest.mark.asyncio async def test_analyze_content_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1677,7 +1639,6 @@ async def test_analyze_content_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse() ) - await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1691,13 +1652,12 @@ async def test_analyze_content_field_headers_async(): def test_analyze_content_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.AnalyzeContentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_content( @@ -1710,14 +1670,12 @@ def test_analyze_content_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") def test_analyze_content_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1732,7 +1690,7 @@ def test_analyze_content_flattened_error(): @pytest.mark.asyncio async def test_analyze_content_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: @@ -1754,15 +1712,13 @@ async def test_analyze_content_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") @pytest.mark.asyncio async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1779,7 +1735,7 @@ def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1792,21 +1748,16 @@ def test_suggest_articles( call.return_value = participant.SuggestArticlesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1818,7 +1769,7 @@ def test_suggest_articles_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1826,7 +1777,6 @@ def test_suggest_articles_empty_call(): client.suggest_articles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() @@ -1835,7 +1785,7 @@ async def test_suggest_articles_async( transport: str = "grpc_asyncio", request_type=participant.SuggestArticlesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1850,20 +1800,16 @@ async def test_suggest_articles_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1873,17 +1819,17 @@ async def test_suggest_articles_async_from_dict(): def test_suggest_articles_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: call.return_value = participant.SuggestArticlesResponse() - client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1898,11 +1844,12 @@ def test_suggest_articles_field_headers(): @pytest.mark.asyncio async def test_suggest_articles_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1910,7 +1857,6 @@ async def test_suggest_articles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestArticlesResponse() ) - await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1924,13 +1870,12 @@ async def test_suggest_articles_field_headers_async(): def test_suggest_articles_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestArticlesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_articles(parent="parent_value",) @@ -1939,12 +1884,11 @@ def test_suggest_articles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_articles_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1956,7 +1900,7 @@ def test_suggest_articles_flattened_error(): @pytest.mark.asyncio async def test_suggest_articles_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: @@ -1974,13 +1918,12 @@ async def test_suggest_articles_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_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1994,7 +1937,7 @@ def test_suggest_faq_answers( transport: str = "grpc", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2009,21 +1952,16 @@ def test_suggest_faq_answers( call.return_value = participant.SuggestFaqAnswersResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2035,7 +1973,7 @@ def test_suggest_faq_answers_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2045,7 +1983,6 @@ def test_suggest_faq_answers_empty_call(): client.suggest_faq_answers() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() @@ -2054,7 +1991,7 @@ async def test_suggest_faq_answers_async( transport: str = "grpc_asyncio", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2071,20 +2008,16 @@ async def test_suggest_faq_answers_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2094,11 +2027,12 @@ async def test_suggest_faq_answers_async_from_dict(): def test_suggest_faq_answers_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2106,7 +2040,6 @@ def test_suggest_faq_answers_field_headers(): type(client.transport.suggest_faq_answers), "__call__" ) as call: call.return_value = participant.SuggestFaqAnswersResponse() - client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2121,11 +2054,12 @@ def test_suggest_faq_answers_field_headers(): @pytest.mark.asyncio async def test_suggest_faq_answers_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2135,7 +2069,6 @@ async def test_suggest_faq_answers_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestFaqAnswersResponse() ) - await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2149,7 +2082,7 @@ async def test_suggest_faq_answers_field_headers_async(): def test_suggest_faq_answers_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2157,7 +2090,6 @@ def test_suggest_faq_answers_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestFaqAnswersResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_faq_answers(parent="parent_value",) @@ -2166,12 +2098,11 @@ def test_suggest_faq_answers_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2183,7 +2114,7 @@ def test_suggest_faq_answers_flattened_error(): @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2203,13 +2134,12 @@ async def test_suggest_faq_answers_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_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2222,16 +2152,16 @@ async def test_suggest_faq_answers_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( - 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.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2241,7 +2171,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2252,7 +2182,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ParticipantsClient(transport=transport) assert client.transport is transport @@ -2261,13 +2191,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2282,23 +2212,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 = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ParticipantsGrpcTransport,) def test_participants_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.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2310,7 +2240,7 @@ def test_participants_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2329,15 +2259,40 @@ def test_participants_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_participants_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.dialogflow_v2.services.participants.transports.ParticipantsTransport._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.ParticipantsTransport( + 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_participants_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.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2353,19 +2308,36 @@ def test_participants_base_transport_with_credentials_file(): def test_participants_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.dialogflow_v2.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_participants_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) + ParticipantsClient() + 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_participants_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) ParticipantsClient() adc.assert_called_once_with( scopes=( @@ -2376,14 +2348,44 @@ def test_participants_auth_adc(): ) -def test_participants_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_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.ParticipantsGrpcTransport( - 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.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_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", @@ -2393,12 +2395,127 @@ def test_participants_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_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.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_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", + 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.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_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", + 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport], ) def test_participants_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: @@ -2440,7 +2557,7 @@ def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class def test_participants_host_no_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2450,7 +2567,7 @@ def test_participants_host_no_port(): def test_participants_host_with_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2501,9 +2618,9 @@ def test_participants_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", @@ -2584,7 +2701,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2608,7 +2724,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2632,7 +2747,6 @@ def test_message_path(): project = "scallop" conversation = "abalone" message = "squid" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2657,7 +2771,6 @@ def test_participant_path(): project = "oyster" conversation = "nudibranch" participant = "cuttlefish" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format( project=project, conversation=conversation, participant=participant, ) @@ -2682,7 +2795,6 @@ def test_session_entity_type_path(): project = "scallop" session = "abalone" entity_type = "squid" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2705,7 +2817,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2726,7 +2837,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = ParticipantsClient.common_folder_path(folder) assert expected == actual @@ -2745,7 +2855,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = ParticipantsClient.common_organization_path(organization) assert expected == actual @@ -2764,7 +2873,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = ParticipantsClient.common_project_path(project) assert expected == actual @@ -2784,7 +2892,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, ) @@ -2811,7 +2918,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ParticipantsTransport, "_prep_wrapped_messages" ) as prep: client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2820,6 +2927,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ParticipantsClient.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/dialogflow_v2/test_session_entity_types.py b/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py index 611435246..396e98c40 100644 --- a/tests/unit/gapic/dialogflow_v2/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2/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.dialogflow_v2.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) from google.cloud.dialogflow_v2.services.session_entity_types import pagers from google.cloud.dialogflow_v2.services.session_entity_types import transports +from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.session_entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import entity_type from google.cloud.dialogflow_v2.types import session_entity_type from google.cloud.dialogflow_v2.types import ( session_entity_type as gcd_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=gcd_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=gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcd_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=gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_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 = gcd_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 = gcd_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 = gcd_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( gcd_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 = gcd_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,16 +1321,16 @@ 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 == gcd_session_entity_type.SessionEntityType( name="name_value" ) 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. @@ -1337,7 +1347,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. @@ -1363,9 +1373,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 == gcd_session_entity_type.SessionEntityType( name="name_value" ) @@ -1374,7 +1382,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 @@ -1394,7 +1402,7 @@ def test_update_session_entity_type( request_type=gcd_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, @@ -1410,21 +1418,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcd_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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1439,7 +1442,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. @@ -1449,7 +1452,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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1459,7 +1461,7 @@ async def test_update_session_entity_type_async( request_type=gcd_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, @@ -1477,20 +1479,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcd_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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1503,11 +1501,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 = gcd_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. @@ -1515,7 +1516,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1534,12 +1534,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 = gcd_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. @@ -1549,7 +1550,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1566,7 +1566,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( @@ -1574,30 +1576,29 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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=gcd_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 == gcd_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. @@ -1607,14 +1608,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcd_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. @@ -1633,25 +1634,23 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcd_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 == gcd_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 @@ -1662,7 +1661,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1671,7 +1670,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, @@ -1684,13 +1683,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. @@ -1705,7 +1702,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. @@ -1715,7 +1712,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() @@ -1725,7 +1721,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, @@ -1738,13 +1734,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. @@ -1757,11 +1751,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. @@ -1769,7 +1766,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. @@ -1785,12 +1781,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. @@ -1798,7 +1795,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. @@ -1812,7 +1808,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( @@ -1820,7 +1818,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",) @@ -1829,12 +1826,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. @@ -1847,7 +1845,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. @@ -1866,14 +1864,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 @@ -1887,16 +1884,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( @@ -1906,7 +1903,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( @@ -1917,7 +1914,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 @@ -1926,13 +1923,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 @@ -1947,23 +1944,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", ) @@ -1975,7 +1974,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 @@ -1992,15 +1991,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.dialogflow_v2.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.dialogflow_v2.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", ) @@ -2016,19 +2040,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.dialogflow_v2.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=( @@ -2039,14 +2080,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", @@ -2056,6 +2127,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", + 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", + 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", [ @@ -2066,7 +2252,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: @@ -2108,7 +2294,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" ), @@ -2118,7 +2304,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" ), @@ -2174,9 +2360,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", @@ -2260,7 +2446,6 @@ def test_session_entity_type_path(): project = "squid" session = "clam" entity_type = "whelk" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2285,7 +2470,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2306,7 +2490,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2325,7 +2508,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2344,7 +2526,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2364,7 +2545,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, ) @@ -2391,7 +2571,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) @@ -2400,6 +2580,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/dialogflow_v2/test_sessions.py b/tests/unit/gapic/dialogflow_v2/test_sessions.py index 8b119b26a..655e9abe6 100644 --- a/tests/unit/gapic/dialogflow_v2/test_sessions.py +++ b/tests/unit/gapic/dialogflow_v2/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.dialogflow_v2.services.sessions import SessionsAsyncClient from google.cloud.dialogflow_v2.services.sessions import SessionsClient from google.cloud.dialogflow_v2.services.sessions import transports +from google.cloud.dialogflow_v2.services.sessions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.sessions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import context from google.cloud.dialogflow_v2.types import entity_type @@ -42,10 +47,34 @@ from google.cloud.dialogflow_v2.types import session as gcd_session from google.cloud.dialogflow_v2.types import 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 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 field_mask_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 +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", [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: @@ -104,7 +133,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: @@ -149,7 +178,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() @@ -425,7 +454,7 @@ def test_detect_intent( transport: str = "grpc", request_type=gcd_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, @@ -438,21 +467,16 @@ def test_detect_intent( call.return_value = gcd_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] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -464,7 +488,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. @@ -472,7 +496,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() @@ -481,7 +504,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -496,20 +519,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] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -519,17 +538,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 = gcd_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 = gcd_session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -544,11 +563,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 = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -556,7 +576,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -570,13 +589,12 @@ async def test_detect_intent_field_headers_async(): def test_detect_intent_flattened(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_session.DetectIntentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_intent( @@ -592,9 +610,7 @@ def test_detect_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -603,7 +619,7 @@ def test_detect_intent_flattened(): def test_detect_intent_flattened_error(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -621,7 +637,7 @@ def test_detect_intent_flattened_error(): @pytest.mark.asyncio async def test_detect_intent_flattened_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: @@ -646,9 +662,7 @@ async def test_detect_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -658,7 +672,7 @@ async def test_detect_intent_flattened_async(): @pytest.mark.asyncio async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -678,13 +692,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. @@ -693,13 +706,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. @@ -716,13 +727,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. @@ -734,13 +744,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. @@ -756,16 +764,16 @@ async def test_streaming_detect_intent_async_from_dict(): 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( @@ -775,7 +783,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( @@ -786,7 +794,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 @@ -795,13 +803,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 @@ -813,23 +821,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", ) @@ -841,7 +849,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 @@ -855,15 +863,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.dialogflow_v2.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", + ) + 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.dialogflow_v2.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", ) @@ -879,19 +912,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.dialogflow_v2.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=( @@ -902,14 +952,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", @@ -919,12 +993,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", + 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", + 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: @@ -966,7 +1151,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" ), @@ -976,7 +1161,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" ), @@ -1027,9 +1212,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", @@ -1110,7 +1295,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -1134,7 +1318,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -1157,7 +1340,6 @@ def test_parse_intent_path(): def test_session_path(): project = "scallop" session = "abalone" - expected = "projects/{project}/agent/sessions/{session}".format( project=project, session=session, ) @@ -1181,7 +1363,6 @@ def test_session_entity_type_path(): project = "whelk" session = "octopus" entity_type = "oyster" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -1204,7 +1385,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1225,7 +1405,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1244,7 +1423,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1263,7 +1441,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1283,7 +1460,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, ) @@ -1310,7 +1486,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) @@ -1319,6 +1495,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/dialogflow_v2/test_versions.py b/tests/unit/gapic/dialogflow_v2/test_versions.py new file mode 100644 index 000000000..26e18a2b4 --- /dev/null +++ b/tests/unit/gapic/dialogflow_v2/test_versions.py @@ -0,0 +1,2273 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2.services.versions import VersionsClient +from google.cloud.dialogflow_v2.services.versions import pagers +from google.cloud.dialogflow_v2.services.versions import transports +from google.cloud.dialogflow_v2.services.versions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2.services.versions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2.types import version +from google.cloud.dialogflow_v2.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# 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(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) +def test_versions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) +def test_versions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) +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=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VersionsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2.services.versions.transports.VersionsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_versions( + transport: str = "grpc", request_type=version.ListVersionsRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + 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" + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async( + transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + 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" + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_versions_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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 = grpc_helpers_async.FakeUnaryUnaryCall( + version.ListVersionsResponse() + ) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_versions_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +def test_list_versions_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_versions( + version.ListVersionsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.ListVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_versions( + version.ListVersionsRequest(), parent="parent_value", + ) + + +def test_list_versions_pager(): + 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: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) for i in results) + + +def test_list_versions_pages(): + 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: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + pages = list(client.list_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_versions_async_pager(): + 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__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + async_pager = await client.list_versions(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, version.Version) for i in responses) + + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + 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__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + 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.description == "description_value" + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +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=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_version), "__call__") as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async( + transport: str = "grpc_asyncio", request_type=version.GetVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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.description == "description_value" + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + 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_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + 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_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # 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_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_version( + version.GetVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version(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_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_version( + version.GetVersionRequest(), name="name_value", + ) + + +def test_create_version( + transport: str = "grpc", request_type=gcd_version.CreateVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + 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] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.CreateVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = gcd_version.Version() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent="parent_value", version=gcd_version.Version(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") + + +def test_create_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_version( + gcd_version.CreateVersionRequest(), + parent="parent_value", + version=gcd_version.Version(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent="parent_value", version=gcd_version.Version(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_version( + gcd_version.CreateVersionRequest(), + parent="parent_value", + version=gcd_version.Version(name="name_value"), + ) + + +def test_update_version( + transport: str = "grpc", request_type=gcd_version.UpdateVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + 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] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.UpdateVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = gcd_version.Version() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] + + +def test_update_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +def test_update_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name="name_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=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_version( + transport: str = "grpc", request_type=version.DeleteVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async( + transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +def test_delete_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_version( + version.DeleteVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_version( + version.DeleteVersionRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_versions", + "get_version", + "create_version", + "update_version", + "delete_version", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@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( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=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.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_versions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = 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(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + 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", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@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", + 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", + 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 = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], +) +def test_versions_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], +) +def test_versions_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder,) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization,) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project,) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/__init__.py b/tests/unit/gapic/dialogflow_v2beta1/__init__.py index 42ffdf2bc..4de65971c 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/__init__.py +++ b/tests/unit/gapic/dialogflow_v2beta1/__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/dialogflow_v2beta1/test_agents.py b/tests/unit/gapic/dialogflow_v2beta1/test_agents.py index ec733fb0b..060c077d5 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_agents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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.dialogflow_v2beta1.services.agents import AgentsAsyncClient from google.cloud.dialogflow_v2beta1.services.agents import AgentsClient from google.cloud.dialogflow_v2beta1.services.agents import pagers from google.cloud.dialogflow_v2beta1.services.agents import transports +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.agents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import agent as gcd_agent from google.cloud.dialogflow_v2beta1.types import validation_result 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_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, @@ -442,41 +471,26 @@ def test_get_agent(transport: str = "grpc", request_type=agent.GetAgentRequest): api_version=agent.Agent.ApiVersion.API_VERSION_V1, tier=agent.Agent.Tier.TIER_STANDARD, ) - 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.parent == "parent_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.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -488,7 +502,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. @@ -496,7 +510,6 @@ def test_get_agent_empty_call(): client.get_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetAgentRequest() @@ -505,7 +518,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, @@ -531,40 +544,26 @@ async def test_get_agent_async( tier=agent.Agent.Tier.TIER_STANDARD, ) ) - 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.parent == "parent_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.enable_logging is True - assert response.match_mode == agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == agent.Agent.Tier.TIER_STANDARD @@ -574,17 +573,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.parent = "parent/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. @@ -599,17 +598,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.parent = "parent/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. @@ -623,13 +622,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(parent="parent_value",) @@ -638,12 +636,11 @@ def test_get_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_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. @@ -655,7 +652,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: @@ -671,13 +668,12 @@ async def test_get_agent_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_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. @@ -689,7 +685,7 @@ async def test_get_agent_flattened_error_async(): def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentRequest): 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, @@ -713,41 +709,26 @@ def test_set_agent(transport: str = "grpc", request_type=gcd_agent.SetAgentReque api_version=gcd_agent.Agent.ApiVersion.API_VERSION_V1, tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) - response = client.set_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] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_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.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -759,7 +740,7 @@ def test_set_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. @@ -767,7 +748,6 @@ def test_set_agent_empty_call(): client.set_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() @@ -776,7 +756,7 @@ async def test_set_agent_async( transport: str = "grpc_asyncio", request_type=gcd_agent.SetAgentRequest ): 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, @@ -802,40 +782,26 @@ async def test_set_agent_async( tier=gcd_agent.Agent.Tier.TIER_STANDARD, ) ) - response = await client.set_agent(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_agent.SetAgentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_agent.Agent) - assert response.parent == "parent_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.enable_logging is True - assert response.match_mode == gcd_agent.Agent.MatchMode.MATCH_MODE_HYBRID - assert math.isclose(response.classification_threshold, 0.2552, rel_tol=1e-6) - assert response.api_version == gcd_agent.Agent.ApiVersion.API_VERSION_V1 - assert response.tier == gcd_agent.Agent.Tier.TIER_STANDARD @@ -845,17 +811,17 @@ async def test_set_agent_async_from_dict(): def test_set_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 = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = gcd_agent.Agent() - client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -872,17 +838,17 @@ def test_set_agent_field_headers(): @pytest.mark.asyncio async def test_set_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 = gcd_agent.SetAgentRequest() + request.agent.parent = "agent.parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_agent), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_agent.Agent()) - await client.set_agent(request) # Establish that the underlying gRPC stub method was called. @@ -898,13 +864,12 @@ async def test_set_agent_field_headers_async(): def test_set_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.set_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_agent.Agent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_agent(agent=gcd_agent.Agent(parent="parent_value"),) @@ -913,12 +878,11 @@ def test_set_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") def test_set_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. @@ -930,7 +894,7 @@ def test_set_agent_flattened_error(): @pytest.mark.asyncio async def test_set_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.set_agent), "__call__") as call: @@ -946,13 +910,12 @@ async def test_set_agent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].agent == gcd_agent.Agent(parent="parent_value") @pytest.mark.asyncio async def test_set_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. @@ -964,7 +927,7 @@ async def test_set_agent_flattened_error_async(): 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, @@ -975,13 +938,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. @@ -996,7 +957,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. @@ -1004,7 +965,6 @@ def test_delete_agent_empty_call(): client.delete_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.DeleteAgentRequest() @@ -1013,7 +973,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, @@ -1024,13 +984,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. @@ -1043,17 +1001,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.parent = "parent/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. @@ -1068,17 +1026,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.parent = "parent/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. @@ -1092,13 +1050,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(parent="parent_value",) @@ -1107,12 +1064,11 @@ def test_delete_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_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. @@ -1124,7 +1080,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: @@ -1140,13 +1096,12 @@ async def test_delete_agent_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_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. @@ -1158,7 +1113,7 @@ async def test_delete_agent_flattened_error_async(): def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsRequest): 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, @@ -1171,19 +1126,15 @@ def test_search_agents(transport: str = "grpc", request_type=agent.SearchAgentsR call.return_value = agent.SearchAgentsResponse( next_page_token="next_page_token_value", ) - response = client.search_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.SearchAgentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAgentsPager) - assert response.next_page_token == "next_page_token_value" @@ -1195,7 +1146,7 @@ def test_search_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. @@ -1203,7 +1154,6 @@ def test_search_agents_empty_call(): client.search_agents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.SearchAgentsRequest() @@ -1212,7 +1162,7 @@ async def test_search_agents_async( transport: str = "grpc_asyncio", request_type=agent.SearchAgentsRequest ): 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, @@ -1225,18 +1175,15 @@ async def test_search_agents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse(next_page_token="next_page_token_value",) ) - response = await client.search_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.SearchAgentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAgentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1246,17 +1193,17 @@ async def test_search_agents_async_from_dict(): def test_search_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.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_agents), "__call__") as call: call.return_value = agent.SearchAgentsResponse() - client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1271,11 +1218,12 @@ def test_search_agents_field_headers(): @pytest.mark.asyncio async def test_search_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.SearchAgentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1283,7 +1231,6 @@ async def test_search_agents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( agent.SearchAgentsResponse() ) - await client.search_agents(request) # Establish that the underlying gRPC stub method was called. @@ -1297,13 +1244,12 @@ async def test_search_agents_field_headers_async(): def test_search_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.search_agents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = agent.SearchAgentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_agents(parent="parent_value",) @@ -1312,12 +1258,11 @@ def test_search_agents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_search_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. @@ -1329,7 +1274,7 @@ def test_search_agents_flattened_error(): @pytest.mark.asyncio async def test_search_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.search_agents), "__call__") as call: @@ -1347,13 +1292,12 @@ async def test_search_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_search_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. @@ -1364,7 +1308,7 @@ async def test_search_agents_flattened_error_async(): def test_search_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.search_agents), "__call__") as call: @@ -1394,7 +1338,7 @@ def test_search_agents_pager(): def test_search_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.search_agents), "__call__") as call: @@ -1416,7 +1360,7 @@ def test_search_agents_pages(): @pytest.mark.asyncio async def test_search_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( @@ -1445,7 +1389,7 @@ async def test_search_agents_async_pager(): @pytest.mark.asyncio async def test_search_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( @@ -1471,7 +1415,7 @@ async def test_search_agents_async_pages(): def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentRequest): 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, @@ -1482,13 +1426,11 @@ def test_train_agent(transport: str = "grpc", request_type=agent.TrainAgentReque with mock.patch.object(type(client.transport.train_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.train_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.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1503,7 +1445,7 @@ def test_train_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. @@ -1511,7 +1453,6 @@ def test_train_agent_empty_call(): client.train_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.TrainAgentRequest() @@ -1520,7 +1461,7 @@ async def test_train_agent_async( transport: str = "grpc_asyncio", request_type=agent.TrainAgentRequest ): 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, @@ -1533,13 +1474,11 @@ async def test_train_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.train_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.TrainAgentRequest() # Establish that the response is the type that we expect. @@ -1552,17 +1491,17 @@ async def test_train_agent_async_from_dict(): def test_train_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.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.train_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1577,11 +1516,12 @@ def test_train_agent_field_headers(): @pytest.mark.asyncio async def test_train_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.TrainAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1589,7 +1529,6 @@ async def test_train_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.train_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1603,13 +1542,12 @@ async def test_train_agent_field_headers_async(): def test_train_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.train_agent), "__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_agent(parent="parent_value",) @@ -1618,12 +1556,11 @@ def test_train_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_train_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. @@ -1635,7 +1572,7 @@ def test_train_agent_flattened_error(): @pytest.mark.asyncio async def test_train_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.train_agent), "__call__") as call: @@ -1653,13 +1590,12 @@ async def test_train_agent_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_train_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. @@ -1671,7 +1607,7 @@ async def test_train_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, @@ -1682,13 +1618,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. @@ -1703,7 +1637,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. @@ -1711,7 +1645,6 @@ def test_export_agent_empty_call(): client.export_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ExportAgentRequest() @@ -1720,7 +1653,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, @@ -1733,13 +1666,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. @@ -1752,17 +1683,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.parent = "parent/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. @@ -1777,11 +1708,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.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1789,7 +1721,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. @@ -1803,13 +1734,12 @@ async def test_export_agent_field_headers_async(): def test_export_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.export_agent), "__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.export_agent(parent="parent_value",) @@ -1818,12 +1748,11 @@ def test_export_agent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_export_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. @@ -1835,7 +1764,7 @@ def test_export_agent_flattened_error(): @pytest.mark.asyncio async def test_export_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.export_agent), "__call__") as call: @@ -1853,13 +1782,12 @@ async def test_export_agent_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_export_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. @@ -1871,7 +1799,7 @@ async def test_export_agent_flattened_error_async(): def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentRequest): 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, @@ -1882,13 +1810,11 @@ def test_import_agent(transport: str = "grpc", request_type=agent.ImportAgentReq with mock.patch.object(type(client.transport.import_agent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_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.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1903,7 +1829,7 @@ def test_import_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. @@ -1911,7 +1837,6 @@ def test_import_agent_empty_call(): client.import_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.ImportAgentRequest() @@ -1920,7 +1845,7 @@ async def test_import_agent_async( transport: str = "grpc_asyncio", request_type=agent.ImportAgentRequest ): 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, @@ -1933,13 +1858,11 @@ async def test_import_agent_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_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.ImportAgentRequest() # Establish that the response is the type that we expect. @@ -1952,17 +1875,17 @@ async def test_import_agent_async_from_dict(): def test_import_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.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_agent), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -1977,11 +1900,12 @@ def test_import_agent_field_headers(): @pytest.mark.asyncio async def test_import_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.ImportAgentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1989,7 +1913,6 @@ async def test_import_agent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_agent(request) # Establish that the underlying gRPC stub method was called. @@ -2004,7 +1927,7 @@ async def test_import_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, @@ -2015,13 +1938,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. @@ -2036,7 +1957,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. @@ -2044,7 +1965,6 @@ def test_restore_agent_empty_call(): client.restore_agent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.RestoreAgentRequest() @@ -2053,7 +1973,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, @@ -2066,13 +1986,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. @@ -2085,17 +2003,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.parent = "parent/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. @@ -2110,11 +2028,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.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2122,7 +2041,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. @@ -2139,7 +2057,7 @@ def test_get_validation_result( transport: str = "grpc", request_type=agent.GetValidationResultRequest ): 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, @@ -2152,17 +2070,14 @@ def test_get_validation_result( ) as call: # Designate an appropriate return value for the call. call.return_value = validation_result.ValidationResult() - response = client.get_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.GetValidationResultRequest() # Establish that the response is the type that we expect. - assert isinstance(response, validation_result.ValidationResult) @@ -2174,7 +2089,7 @@ def test_get_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. @@ -2184,7 +2099,6 @@ def test_get_validation_result_empty_call(): client.get_validation_result() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == agent.GetValidationResultRequest() @@ -2193,7 +2107,7 @@ async def test_get_validation_result_async( transport: str = "grpc_asyncio", request_type=agent.GetValidationResultRequest ): 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, @@ -2208,13 +2122,11 @@ async def test_get_validation_result_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - response = await client.get_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.GetValidationResultRequest() # Establish that the response is the type that we expect. @@ -2227,11 +2139,12 @@ async def test_get_validation_result_async_from_dict(): def test_get_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.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2239,7 +2152,6 @@ def test_get_validation_result_field_headers(): type(client.transport.get_validation_result), "__call__" ) as call: call.return_value = validation_result.ValidationResult() - client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2254,11 +2166,12 @@ def test_get_validation_result_field_headers(): @pytest.mark.asyncio async def test_get_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.GetValidationResultRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2268,7 +2181,6 @@ async def test_get_validation_result_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( validation_result.ValidationResult() ) - await client.get_validation_result(request) # Establish that the underlying gRPC stub method was called. @@ -2284,16 +2196,16 @@ async def test_get_validation_result_field_headers_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( @@ -2303,7 +2215,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( @@ -2314,7 +2226,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 @@ -2323,13 +2235,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 @@ -2341,23 +2253,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", ) @@ -2369,7 +2281,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 @@ -2395,15 +2307,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.dialogflow_v2beta1.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.dialogflow_v2beta1.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", ) @@ -2419,19 +2356,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.dialogflow_v2beta1.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=( @@ -2442,14 +2396,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", @@ -2459,12 +2437,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", + 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", + 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: @@ -2506,7 +2595,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" ), @@ -2516,7 +2605,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" ), @@ -2567,9 +2656,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", @@ -2648,7 +2737,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 @@ -2661,7 +2750,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 @@ -2674,7 +2763,6 @@ def test_agents_grpc_lro_async_client(): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = AgentsClient.agent_path(project) assert expected == actual @@ -2693,7 +2781,6 @@ def test_parse_agent_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2714,7 +2801,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = AgentsClient.common_folder_path(folder) assert expected == actual @@ -2733,7 +2819,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = AgentsClient.common_organization_path(organization) assert expected == actual @@ -2752,7 +2837,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = AgentsClient.common_project_path(project) assert expected == actual @@ -2772,7 +2856,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2799,7 +2882,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) @@ -2808,6 +2891,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/dialogflow_v2beta1/test_answer_records.py b/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py index 06408100c..ebaf78a56 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.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.dialogflow_v2beta1.services.answer_records import ( AnswerRecordsAsyncClient, @@ -38,12 +37,42 @@ from google.cloud.dialogflow_v2beta1.services.answer_records import AnswerRecordsClient from google.cloud.dialogflow_v2beta1.services.answer_records import pagers from google.cloud.dialogflow_v2beta1.services.answer_records import transports +from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.answer_records.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import answer_record from google.cloud.dialogflow_v2beta1.types import answer_record as gcd_answer_record from google.cloud.dialogflow_v2beta1.types import participant from google.oauth2 import service_account -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 +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(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_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: @@ -111,7 +140,7 @@ def test_answer_records_client_from_service_account_info(client_class): "client_class", [AnswerRecordsClient, AnswerRecordsAsyncClient,] ) def test_answer_records_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: @@ -164,7 +193,7 @@ def test_answer_records_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(AnswerRecordsClient, "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() @@ -452,7 +481,7 @@ def test_get_answer_record( transport: str = "grpc", request_type=answer_record.GetAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -470,19 +499,15 @@ def test_get_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, answer_record.AnswerRecord) - assert response.name == "name_value" @@ -494,7 +519,7 @@ def test_get_answer_record_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 = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -504,7 +529,6 @@ def test_get_answer_record_empty_call(): client.get_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() @@ -513,7 +537,7 @@ async def test_get_answer_record_async( transport: str = "grpc_asyncio", request_type=answer_record.GetAnswerRecordRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -528,18 +552,15 @@ async def test_get_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.AnswerRecord(name="name_value",) ) - response = await client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.GetAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, answer_record.AnswerRecord) - assert response.name == "name_value" @@ -549,11 +570,12 @@ async def test_get_answer_record_async_from_dict(): def test_get_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.GetAnswerRecordRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -561,7 +583,6 @@ def test_get_answer_record_field_headers(): type(client.transport.get_answer_record), "__call__" ) as call: call.return_value = answer_record.AnswerRecord() - client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -576,11 +597,14 @@ def test_get_answer_record_field_headers(): @pytest.mark.asyncio async def test_get_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.GetAnswerRecordRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ async def test_get_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.AnswerRecord() ) - await client.get_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -607,7 +630,7 @@ def test_list_answer_records( transport: str = "grpc", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -622,19 +645,15 @@ def test_list_answer_records( call.return_value = answer_record.ListAnswerRecordsResponse( next_page_token="next_page_token_value", ) - response = client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAnswerRecordsPager) - assert response.next_page_token == "next_page_token_value" @@ -646,7 +665,7 @@ def test_list_answer_records_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 = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -656,7 +675,6 @@ def test_list_answer_records_empty_call(): client.list_answer_records() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() @@ -665,7 +683,7 @@ async def test_list_answer_records_async( transport: str = "grpc_asyncio", request_type=answer_record.ListAnswerRecordsRequest ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -682,18 +700,15 @@ async def test_list_answer_records_async( next_page_token="next_page_token_value", ) ) - response = await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == answer_record.ListAnswerRecordsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAnswerRecordsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -703,11 +718,12 @@ async def test_list_answer_records_async_from_dict(): def test_list_answer_records_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -715,7 +731,6 @@ def test_list_answer_records_field_headers(): type(client.transport.list_answer_records), "__call__" ) as call: call.return_value = answer_record.ListAnswerRecordsResponse() - client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -730,11 +745,14 @@ def test_list_answer_records_field_headers(): @pytest.mark.asyncio async def test_list_answer_records_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = answer_record.ListAnswerRecordsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -744,7 +762,6 @@ async def test_list_answer_records_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( answer_record.ListAnswerRecordsResponse() ) - await client.list_answer_records(request) # Establish that the underlying gRPC stub method was called. @@ -758,7 +775,7 @@ async def test_list_answer_records_field_headers_async(): def test_list_answer_records_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -766,7 +783,6 @@ def test_list_answer_records_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = answer_record.ListAnswerRecordsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_answer_records(parent="parent_value",) @@ -775,12 +791,11 @@ def test_list_answer_records_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_answer_records_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -792,7 +807,9 @@ def test_list_answer_records_flattened_error(): @pytest.mark.asyncio async def test_list_answer_records_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -812,13 +829,14 @@ async def test_list_answer_records_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_answer_records_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -829,7 +847,7 @@ async def test_list_answer_records_flattened_error_async(): def test_list_answer_records_pager(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -874,7 +892,7 @@ def test_list_answer_records_pager(): def test_list_answer_records_pages(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -911,7 +929,7 @@ def test_list_answer_records_pages(): @pytest.mark.asyncio async def test_list_answer_records_async_pager(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -955,7 +973,7 @@ async def test_list_answer_records_async_pager(): @pytest.mark.asyncio async def test_list_answer_records_async_pages(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AnswerRecordsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -998,7 +1016,7 @@ def test_update_answer_record( transport: str = "grpc", request_type=gcd_answer_record.UpdateAnswerRecordRequest ): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1016,19 +1034,15 @@ def test_update_answer_record( article_suggestion_answer=participant.ArticleAnswer(title="title_value") ), ) - response = client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -1040,7 +1054,7 @@ def test_update_answer_record_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 = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1050,7 +1064,6 @@ def test_update_answer_record_empty_call(): client.update_answer_record() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() @@ -1060,7 +1073,7 @@ async def test_update_answer_record_async( request_type=gcd_answer_record.UpdateAnswerRecordRequest, ): client = AnswerRecordsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1075,18 +1088,15 @@ async def test_update_answer_record_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord(name="name_value",) ) - response = await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_answer_record.UpdateAnswerRecordRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_answer_record.AnswerRecord) - assert response.name == "name_value" @@ -1096,11 +1106,12 @@ async def test_update_answer_record_async_from_dict(): def test_update_answer_record_field_headers(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1108,7 +1119,6 @@ def test_update_answer_record_field_headers(): type(client.transport.update_answer_record), "__call__" ) as call: call.return_value = gcd_answer_record.AnswerRecord() - client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1126,11 +1136,14 @@ def test_update_answer_record_field_headers(): @pytest.mark.asyncio async def test_update_answer_record_field_headers_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_answer_record.UpdateAnswerRecordRequest() + request.answer_record.name = "answer_record.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1140,7 +1153,6 @@ async def test_update_answer_record_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_answer_record.AnswerRecord() ) - await client.update_answer_record(request) # Establish that the underlying gRPC stub method was called. @@ -1157,7 +1169,7 @@ async def test_update_answer_record_field_headers_async(): def test_update_answer_record_flattened(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1165,28 +1177,25 @@ def test_update_answer_record_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_answer_record.AnswerRecord() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(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].answer_record == gcd_answer_record.AnswerRecord( 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_answer_record_flattened_error(): - client = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1194,13 +1203,15 @@ def test_update_answer_record_flattened_error(): client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(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_answer_record_flattened_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1216,24 +1227,24 @@ async def test_update_answer_record_flattened_async(): # using the keyword arguments to the method. response = await client.update_answer_record( answer_record=gcd_answer_record.AnswerRecord(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].answer_record == gcd_answer_record.AnswerRecord( 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_answer_record_flattened_error_async(): - client = AnswerRecordsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1241,23 +1252,23 @@ async def test_update_answer_record_flattened_error_async(): await client.update_answer_record( gcd_answer_record.UpdateAnswerRecordRequest(), answer_record=gcd_answer_record.AnswerRecord(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( - 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.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1267,7 +1278,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AnswerRecordsClient( @@ -1278,7 +1289,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AnswerRecordsClient(transport=transport) assert client.transport is transport @@ -1287,13 +1298,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AnswerRecordsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AnswerRecordsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1308,23 +1319,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 = AnswerRecordsClient(credentials=credentials.AnonymousCredentials(),) + client = AnswerRecordsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.AnswerRecordsGrpcTransport,) def test_answer_records_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.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1336,7 +1347,7 @@ def test_answer_records_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AnswerRecordsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1351,15 +1362,40 @@ def test_answer_records_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_answer_records_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.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._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.AnswerRecordsTransport( + 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_answer_records_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.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1375,19 +1411,36 @@ def test_answer_records_base_transport_with_credentials_file(): def test_answer_records_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.dialogflow_v2beta1.services.answer_records.transports.AnswerRecordsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AnswerRecordsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_answer_records_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) + AnswerRecordsClient() + 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_answer_records_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) AnswerRecordsClient() adc.assert_called_once_with( scopes=( @@ -1398,14 +1451,44 @@ def test_answer_records_auth_adc(): ) -def test_answer_records_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_answer_records_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.AnswerRecordsGrpcTransport( - 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.AnswerRecordsGrpcTransport, + transports.AnswerRecordsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_answer_records_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", @@ -1415,6 +1498,121 @@ def test_answer_records_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_answer_records_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.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_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", + 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.AnswerRecordsGrpcTransport, grpc_helpers), + (transports.AnswerRecordsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_answer_records_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", + 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", [ @@ -1423,7 +1621,7 @@ def test_answer_records_transport_auth_adc(): ], ) def test_answer_records_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: @@ -1465,7 +1663,7 @@ def test_answer_records_grpc_transport_client_cert_source_for_mtls(transport_cla def test_answer_records_host_no_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -1475,7 +1673,7 @@ def test_answer_records_host_no_port(): def test_answer_records_host_with_port(): client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -1529,9 +1727,9 @@ def test_answer_records_transport_channel_mtls_with_client_cert_source(transport 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", @@ -1614,7 +1812,6 @@ def test_answer_records_transport_channel_mtls_with_adc(transport_class): def test_answer_record_path(): project = "squid" answer_record = "clam" - expected = "projects/{project}/answerRecords/{answer_record}".format( project=project, answer_record=answer_record, ) @@ -1636,7 +1833,6 @@ def test_parse_answer_record_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1657,7 +1853,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AnswerRecordsClient.common_folder_path(folder) assert expected == actual @@ -1676,7 +1871,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AnswerRecordsClient.common_organization_path(organization) assert expected == actual @@ -1695,7 +1889,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AnswerRecordsClient.common_project_path(project) assert expected == actual @@ -1715,7 +1908,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, ) @@ -1742,7 +1934,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AnswerRecordsTransport, "_prep_wrapped_messages" ) as prep: client = AnswerRecordsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1751,6 +1943,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AnswerRecordsClient.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/dialogflow_v2beta1/test_contexts.py b/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py index dcdec7af4..ac0417f89 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_contexts.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_contexts.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.dialogflow_v2beta1.services.contexts import ContextsAsyncClient from google.cloud.dialogflow_v2beta1.services.contexts import ContextsClient from google.cloud.dialogflow_v2beta1.services.contexts import pagers from google.cloud.dialogflow_v2beta1.services.contexts import transports +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.contexts.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import context as gcd_context 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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_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_contexts_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ContextsClient, ContextsAsyncClient,]) def test_contexts_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_contexts_client_get_transport_class(): def test_contexts_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(ContextsClient, "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_contexts( transport: str = "grpc", request_type=context.ListContextsRequest ): client = ContextsClient( - 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_contexts( call.return_value = context.ListContextsResponse( next_page_token="next_page_token_value", ) - response = client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListContextsPager) - assert response.next_page_token == "next_page_token_value" @@ -457,7 +482,7 @@ def test_list_contexts_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 = ContextsClient( - 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_contexts_empty_call(): client.list_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() @@ -474,7 +498,7 @@ async def test_list_contexts_async( transport: str = "grpc_asyncio", request_type=context.ListContextsRequest ): client = ContextsAsyncClient( - 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_contexts_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.ListContextsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListContextsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -508,17 +529,17 @@ async def test_list_contexts_async_from_dict(): def test_list_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: call.return_value = context.ListContextsResponse() - client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -533,11 +554,12 @@ def test_list_contexts_field_headers(): @pytest.mark.asyncio async def test_list_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.ListContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -545,7 +567,6 @@ async def test_list_contexts_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.ListContextsResponse() ) - await client.list_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -559,13 +580,12 @@ async def test_list_contexts_field_headers_async(): def test_list_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.ListContextsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_contexts(parent="parent_value",) @@ -574,12 +594,11 @@ def test_list_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(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_contexts_flattened_error(): @pytest.mark.asyncio async def test_list_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -609,13 +628,12 @@ async def test_list_contexts_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_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(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_contexts_flattened_error_async(): def test_list_contexts_pager(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -660,7 +678,7 @@ def test_list_contexts_pager(): def test_list_contexts_pages(): - client = ContextsClient(credentials=credentials.AnonymousCredentials,) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_contexts), "__call__") as call: @@ -686,7 +704,7 @@ def test_list_contexts_pages(): @pytest.mark.asyncio async def test_list_contexts_async_pager(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(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_contexts_async_pager(): @pytest.mark.asyncio async def test_list_contexts_async_pages(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ContextsAsyncClient(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_contexts_async_pages(): def test_get_context(transport: str = "grpc", request_type=context.GetContextRequest): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -760,21 +778,16 @@ def test_get_context(transport: str = "grpc", request_type=context.GetContextReq with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context(name="name_value", lifespan_count=1498,) - response = client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -786,7 +799,7 @@ def test_get_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -794,7 +807,6 @@ def test_get_context_empty_call(): client.get_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() @@ -803,7 +815,7 @@ async def test_get_context_async( transport: str = "grpc_asyncio", request_type=context.GetContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -816,20 +828,16 @@ async def test_get_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.get_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.GetContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -839,17 +847,17 @@ async def test_get_context_async_from_dict(): def test_get_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = context.Context() - client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -864,17 +872,17 @@ def test_get_context_field_headers(): @pytest.mark.asyncio async def test_get_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.GetContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(context.Context()) - await client.get_context(request) # Establish that the underlying gRPC stub method was called. @@ -888,13 +896,12 @@ async def test_get_context_field_headers_async(): def test_get_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_context(name="name_value",) @@ -903,12 +910,11 @@ def test_get_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -920,7 +926,7 @@ def test_get_context_flattened_error(): @pytest.mark.asyncio async def test_get_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_context), "__call__") as call: @@ -936,13 +942,12 @@ async def test_get_context_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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -956,7 +961,7 @@ def test_create_context( transport: str = "grpc", request_type=gcd_context.CreateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -967,21 +972,16 @@ def test_create_context( with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -993,7 +993,7 @@ def test_create_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +1001,6 @@ def test_create_context_empty_call(): client.create_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() @@ -1010,7 +1009,7 @@ async def test_create_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.CreateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1023,20 +1022,16 @@ async def test_create_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.create_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.CreateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1046,17 +1041,17 @@ async def test_create_context_async_from_dict(): def test_create_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = gcd_context.Context() - client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1071,17 +1066,17 @@ def test_create_context_field_headers(): @pytest.mark.asyncio async def test_create_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.CreateContextRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.create_context(request) # Establish that the underlying gRPC stub method was called. @@ -1095,13 +1090,12 @@ async def test_create_context_field_headers_async(): def test_create_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_context( @@ -1112,14 +1106,12 @@ def test_create_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") def test_create_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1133,7 +1125,7 @@ def test_create_context_flattened_error(): @pytest.mark.asyncio async def test_create_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_context), "__call__") as call: @@ -1151,15 +1143,13 @@ async def test_create_context_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].context == gcd_context.Context(name="name_value") @pytest.mark.asyncio async def test_create_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1175,7 +1165,7 @@ def test_update_context( transport: str = "grpc", request_type=gcd_context.UpdateContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1186,21 +1176,16 @@ def test_update_context( with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context(name="name_value", lifespan_count=1498,) - response = client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1212,7 +1197,7 @@ def test_update_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1220,7 +1205,6 @@ def test_update_context_empty_call(): client.update_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() @@ -1229,7 +1213,7 @@ async def test_update_context_async( transport: str = "grpc_asyncio", request_type=gcd_context.UpdateContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1242,20 +1226,16 @@ async def test_update_context_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_context.Context(name="name_value", lifespan_count=1498,) ) - response = await client.update_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_context.UpdateContextRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_context.Context) - assert response.name == "name_value" - assert response.lifespan_count == 1498 @@ -1265,17 +1245,17 @@ async def test_update_context_async_from_dict(): def test_update_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = gcd_context.Context() - client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1292,17 +1272,17 @@ def test_update_context_field_headers(): @pytest.mark.asyncio async def test_update_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_context.UpdateContextRequest() + request.context.name = "context.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_context.Context()) - await client.update_context(request) # Establish that the underlying gRPC stub method was called. @@ -1318,32 +1298,29 @@ async def test_update_context_field_headers_async(): def test_update_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_context.Context() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_context( context=gcd_context.Context(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].context == gcd_context.Context(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_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1351,13 +1328,13 @@ def test_update_context_flattened_error(): client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(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_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_context), "__call__") as call: @@ -1369,22 +1346,20 @@ async def test_update_context_flattened_async(): # using the keyword arguments to the method. response = await client.update_context( context=gcd_context.Context(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].context == gcd_context.Context(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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1392,7 +1367,7 @@ async def test_update_context_flattened_error_async(): await client.update_context( gcd_context.UpdateContextRequest(), context=gcd_context.Context(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1400,7 +1375,7 @@ def test_delete_context( transport: str = "grpc", request_type=context.DeleteContextRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1411,13 +1386,11 @@ def test_delete_context( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1432,7 +1405,7 @@ def test_delete_context_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1440,7 +1413,6 @@ def test_delete_context_empty_call(): client.delete_context() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() @@ -1449,7 +1421,7 @@ async def test_delete_context_async( transport: str = "grpc_asyncio", request_type=context.DeleteContextRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1460,13 +1432,11 @@ async def test_delete_context_async( with mock.patch.object(type(client.transport.delete_context), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_context(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteContextRequest() # Establish that the response is the type that we expect. @@ -1479,17 +1449,17 @@ async def test_delete_context_async_from_dict(): def test_delete_context_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = None - client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1504,17 +1474,17 @@ def test_delete_context_field_headers(): @pytest.mark.asyncio async def test_delete_context_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteContextRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_context(request) # Establish that the underlying gRPC stub method was called. @@ -1528,13 +1498,12 @@ async def test_delete_context_field_headers_async(): def test_delete_context_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__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_context(name="name_value",) @@ -1543,12 +1512,11 @@ def test_delete_context_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_context_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1560,7 +1528,7 @@ def test_delete_context_flattened_error(): @pytest.mark.asyncio async def test_delete_context_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_context), "__call__") as call: @@ -1576,13 +1544,12 @@ async def test_delete_context_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_context_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1596,7 +1563,7 @@ def test_delete_all_contexts( transport: str = "grpc", request_type=context.DeleteAllContextsRequest ): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1609,13 +1576,11 @@ def test_delete_all_contexts( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1630,7 +1595,7 @@ def test_delete_all_contexts_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 = ContextsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1640,7 +1605,6 @@ def test_delete_all_contexts_empty_call(): client.delete_all_contexts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() @@ -1649,7 +1613,7 @@ async def test_delete_all_contexts_async( transport: str = "grpc_asyncio", request_type=context.DeleteAllContextsRequest ): client = ContextsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1626,11 @@ async def test_delete_all_contexts_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == context.DeleteAllContextsRequest() # Establish that the response is the type that we expect. @@ -1681,11 +1643,12 @@ async def test_delete_all_contexts_async_from_dict(): def test_delete_all_contexts_field_headers(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1693,7 +1656,6 @@ def test_delete_all_contexts_field_headers(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = None - client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1708,11 +1670,12 @@ def test_delete_all_contexts_field_headers(): @pytest.mark.asyncio async def test_delete_all_contexts_field_headers_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = context.DeleteAllContextsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1720,7 +1683,6 @@ async def test_delete_all_contexts_field_headers_async(): type(client.transport.delete_all_contexts), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_all_contexts(request) # Establish that the underlying gRPC stub method was called. @@ -1734,7 +1696,7 @@ async def test_delete_all_contexts_field_headers_async(): def test_delete_all_contexts_flattened(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1742,7 +1704,6 @@ def test_delete_all_contexts_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_all_contexts(parent="parent_value",) @@ -1751,12 +1712,11 @@ def test_delete_all_contexts_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_delete_all_contexts_flattened_error(): - client = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1768,7 +1728,7 @@ def test_delete_all_contexts_flattened_error(): @pytest.mark.asyncio async def test_delete_all_contexts_flattened_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1786,13 +1746,12 @@ async def test_delete_all_contexts_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_delete_all_contexts_flattened_error_async(): - client = ContextsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1805,16 +1764,16 @@ async def test_delete_all_contexts_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( - 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.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1824,7 +1783,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ContextsClient( @@ -1835,7 +1794,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ContextsClient(transport=transport) assert client.transport is transport @@ -1844,13 +1803,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ContextsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ContextsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1862,23 +1821,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 = ContextsClient(credentials=credentials.AnonymousCredentials(),) + client = ContextsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ContextsGrpcTransport,) def test_contexts_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.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1890,7 +1849,7 @@ def test_contexts_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ContextsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1908,15 +1867,40 @@ def test_contexts_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_contexts_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.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ContextsTransport( + 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_contexts_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.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._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.ContextsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1932,19 +1916,36 @@ def test_contexts_base_transport_with_credentials_file(): def test_contexts_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.dialogflow_v2beta1.services.contexts.transports.ContextsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ContextsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_contexts_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) + ContextsClient() + 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_contexts_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) ContextsClient() adc.assert_called_once_with( scopes=( @@ -1955,14 +1956,38 @@ def test_contexts_auth_adc(): ) -def test_contexts_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_contexts_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.ContextsGrpcTransport( - 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_contexts_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", @@ -1972,12 +1997,123 @@ def test_contexts_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_contexts_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.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_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", + 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.ContextsGrpcTransport, grpc_helpers), + (transports.ContextsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_contexts_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", + 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.ContextsGrpcTransport, transports.ContextsGrpcAsyncIOTransport], ) def test_contexts_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: @@ -2019,7 +2155,7 @@ def test_contexts_grpc_transport_client_cert_source_for_mtls(transport_class): def test_contexts_host_no_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2029,7 +2165,7 @@ def test_contexts_host_no_port(): def test_contexts_host_with_port(): client = ContextsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2080,9 +2216,9 @@ def test_contexts_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", @@ -2163,7 +2299,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2186,7 +2321,6 @@ def test_parse_context_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2207,7 +2341,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = ContextsClient.common_folder_path(folder) assert expected == actual @@ -2226,7 +2359,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = ContextsClient.common_organization_path(organization) assert expected == actual @@ -2245,7 +2377,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = ContextsClient.common_project_path(project) assert expected == actual @@ -2265,7 +2396,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, ) @@ -2292,7 +2422,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ContextsTransport, "_prep_wrapped_messages" ) as prep: client = ContextsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2301,6 +2431,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ContextsClient.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/dialogflow_v2beta1/test_conversation_profiles.py b/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py index 8aa9c1358..f1104a98b 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_conversation_profiles.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.dialogflow_v2beta1.services.conversation_profiles import ( ConversationProfilesAsyncClient, @@ -40,6 +39,12 @@ ) from google.cloud.dialogflow_v2beta1.services.conversation_profiles import pagers from google.cloud.dialogflow_v2beta1.services.conversation_profiles import transports +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.conversation_profiles.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import conversation_profile from google.cloud.dialogflow_v2beta1.types import ( @@ -47,8 +52,32 @@ ) from google.cloud.dialogflow_v2beta1.types import participant from google.oauth2 import service_account -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 +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(): @@ -100,7 +129,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_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: @@ -117,7 +146,7 @@ def test_conversation_profiles_client_from_service_account_info(client_class): "client_class", [ConversationProfilesClient, ConversationProfilesAsyncClient,] ) def test_conversation_profiles_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: @@ -174,7 +203,7 @@ def test_conversation_profiles_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationProfilesClient, "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() @@ -481,7 +510,7 @@ def test_list_conversation_profiles( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -496,19 +525,15 @@ def test_list_conversation_profiles( call.return_value = conversation_profile.ListConversationProfilesResponse( next_page_token="next_page_token_value", ) - response = client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationProfilesPager) - assert response.next_page_token == "next_page_token_value" @@ -520,7 +545,7 @@ def test_list_conversation_profiles_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -530,7 +555,6 @@ def test_list_conversation_profiles_empty_call(): client.list_conversation_profiles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() @@ -540,7 +564,7 @@ async def test_list_conversation_profiles_async( request_type=conversation_profile.ListConversationProfilesRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -557,18 +581,15 @@ async def test_list_conversation_profiles_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.ListConversationProfilesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationProfilesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -578,11 +599,14 @@ async def test_list_conversation_profiles_async_from_dict(): def test_list_conversation_profiles_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ def test_list_conversation_profiles_field_headers(): type(client.transport.list_conversation_profiles), "__call__" ) as call: call.return_value = conversation_profile.ListConversationProfilesResponse() - client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -606,12 +629,13 @@ def test_list_conversation_profiles_field_headers(): @pytest.mark.asyncio async def test_list_conversation_profiles_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.ListConversationProfilesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -621,7 +645,6 @@ async def test_list_conversation_profiles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ListConversationProfilesResponse() ) - await client.list_conversation_profiles(request) # Establish that the underlying gRPC stub method was called. @@ -635,7 +658,9 @@ async def test_list_conversation_profiles_field_headers_async(): def test_list_conversation_profiles_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -643,7 +668,6 @@ def test_list_conversation_profiles_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ListConversationProfilesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversation_profiles(parent="parent_value",) @@ -652,12 +676,13 @@ def test_list_conversation_profiles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversation_profiles_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -671,7 +696,7 @@ def test_list_conversation_profiles_flattened_error(): @pytest.mark.asyncio async def test_list_conversation_profiles_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -692,14 +717,13 @@ async def test_list_conversation_profiles_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_conversation_profiles_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -712,7 +736,9 @@ async def test_list_conversation_profiles_flattened_error_async(): def test_list_conversation_profiles_pager(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -760,7 +786,9 @@ def test_list_conversation_profiles_pager(): def test_list_conversation_profiles_pages(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials,) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials, + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -799,7 +827,7 @@ def test_list_conversation_profiles_pages(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pager(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -848,7 +876,7 @@ async def test_list_conversation_profiles_async_pager(): @pytest.mark.asyncio async def test_list_conversation_profiles_async_pages(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. @@ -894,7 +922,7 @@ def test_get_conversation_profile( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -911,23 +939,17 @@ def test_get_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -939,7 +961,7 @@ def test_get_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -949,7 +971,6 @@ def test_get_conversation_profile_empty_call(): client.get_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() @@ -959,7 +980,7 @@ async def test_get_conversation_profile_async( request_type=conversation_profile.GetConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -978,22 +999,17 @@ async def test_get_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.GetConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1003,11 +1019,14 @@ async def test_get_conversation_profile_async_from_dict(): def test_get_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1015,7 +1034,6 @@ def test_get_conversation_profile_field_headers(): type(client.transport.get_conversation_profile), "__call__" ) as call: call.return_value = conversation_profile.ConversationProfile() - client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1031,12 +1049,13 @@ def test_get_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_get_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.GetConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1046,7 +1065,6 @@ async def test_get_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation_profile.ConversationProfile() ) - await client.get_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1060,7 +1078,9 @@ async def test_get_conversation_profile_field_headers_async(): def test_get_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1068,7 +1088,6 @@ def test_get_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation_profile(name="name_value",) @@ -1077,12 +1096,13 @@ def test_get_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1095,7 +1115,7 @@ def test_get_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1116,14 +1136,13 @@ async def test_get_conversation_profile_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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1139,7 +1158,7 @@ def test_create_conversation_profile( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1156,23 +1175,17 @@ def test_create_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1184,7 +1197,7 @@ def test_create_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1194,7 +1207,6 @@ def test_create_conversation_profile_empty_call(): client.create_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() @@ -1204,7 +1216,7 @@ async def test_create_conversation_profile_async( request_type=gcd_conversation_profile.CreateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1223,22 +1235,17 @@ async def test_create_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.CreateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1248,11 +1255,14 @@ async def test_create_conversation_profile_async_from_dict(): def test_create_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1260,7 +1270,6 @@ def test_create_conversation_profile_field_headers(): type(client.transport.create_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1276,12 +1285,13 @@ def test_create_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_create_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = gcd_conversation_profile.CreateConversationProfileRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1291,7 +1301,6 @@ async def test_create_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.create_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1305,7 +1314,9 @@ async def test_create_conversation_profile_field_headers_async(): def test_create_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1313,7 +1324,6 @@ def test_create_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation_profile( @@ -1327,9 +1337,7 @@ def test_create_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1338,7 +1346,9 @@ def test_create_conversation_profile_flattened(): def test_create_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1355,7 +1365,7 @@ def test_create_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1381,9 +1391,7 @@ async def test_create_conversation_profile_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[ 0 ].conversation_profile == gcd_conversation_profile.ConversationProfile( @@ -1394,7 +1402,7 @@ async def test_create_conversation_profile_flattened_async(): @pytest.mark.asyncio async def test_create_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1414,7 +1422,7 @@ def test_update_conversation_profile( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1431,23 +1439,17 @@ def test_update_conversation_profile( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1459,7 +1461,7 @@ def test_update_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1469,7 +1471,6 @@ def test_update_conversation_profile_empty_call(): client.update_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() @@ -1479,7 +1480,7 @@ async def test_update_conversation_profile_async( request_type=gcd_conversation_profile.UpdateConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1498,22 +1499,17 @@ async def test_update_conversation_profile_async( language_code="language_code_value", ) ) - response = await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation_profile.UpdateConversationProfileRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation_profile.ConversationProfile) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1523,11 +1519,14 @@ async def test_update_conversation_profile_async_from_dict(): def test_update_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1535,7 +1534,6 @@ def test_update_conversation_profile_field_headers(): type(client.transport.update_conversation_profile), "__call__" ) as call: call.return_value = gcd_conversation_profile.ConversationProfile() - client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1554,12 +1552,13 @@ def test_update_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_update_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = gcd_conversation_profile.UpdateConversationProfileRequest() + request.conversation_profile.name = "conversation_profile.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1569,7 +1568,6 @@ async def test_update_conversation_profile_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation_profile.ConversationProfile() ) - await client.update_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1586,7 +1584,9 @@ async def test_update_conversation_profile_field_headers_async(): def test_update_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1594,32 +1594,31 @@ def test_update_conversation_profile_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation_profile.ConversationProfile() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_conversation_profile( conversation_profile=gcd_conversation_profile.ConversationProfile( 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 ].conversation_profile == gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1629,14 +1628,14 @@ def test_update_conversation_profile_flattened_error(): conversation_profile=gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1655,27 +1654,25 @@ async def test_update_conversation_profile_flattened_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( 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 ].conversation_profile == gcd_conversation_profile.ConversationProfile( 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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1686,7 +1683,7 @@ async def test_update_conversation_profile_flattened_error_async(): conversation_profile=gcd_conversation_profile.ConversationProfile( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1695,7 +1692,7 @@ def test_delete_conversation_profile( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1708,13 +1705,11 @@ def test_delete_conversation_profile( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1729,7 +1724,7 @@ def test_delete_conversation_profile_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 = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1739,7 +1734,6 @@ def test_delete_conversation_profile_empty_call(): client.delete_conversation_profile() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() @@ -1749,7 +1743,7 @@ async def test_delete_conversation_profile_async( request_type=conversation_profile.DeleteConversationProfileRequest, ): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1762,13 +1756,11 @@ async def test_delete_conversation_profile_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation_profile.DeleteConversationProfileRequest() # Establish that the response is the type that we expect. @@ -1781,11 +1773,14 @@ async def test_delete_conversation_profile_async_from_dict(): def test_delete_conversation_profile_field_headers(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1793,7 +1788,6 @@ def test_delete_conversation_profile_field_headers(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = None - client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1809,12 +1803,13 @@ def test_delete_conversation_profile_field_headers(): @pytest.mark.asyncio async def test_delete_conversation_profile_field_headers_async(): client = ConversationProfilesAsyncClient( - 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 = conversation_profile.DeleteConversationProfileRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1822,7 +1817,6 @@ async def test_delete_conversation_profile_field_headers_async(): type(client.transport.delete_conversation_profile), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_conversation_profile(request) # Establish that the underlying gRPC stub method was called. @@ -1836,7 +1830,9 @@ async def test_delete_conversation_profile_field_headers_async(): def test_delete_conversation_profile_flattened(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1844,7 +1840,6 @@ def test_delete_conversation_profile_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_conversation_profile(name="name_value",) @@ -1853,12 +1848,13 @@ def test_delete_conversation_profile_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_conversation_profile_flattened_error(): - client = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1871,7 +1867,7 @@ def test_delete_conversation_profile_flattened_error(): @pytest.mark.asyncio async def test_delete_conversation_profile_flattened_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1890,14 +1886,13 @@ async def test_delete_conversation_profile_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_conversation_profile_flattened_error_async(): client = ConversationProfilesAsyncClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Attempting to call a method with both a request object and flattened @@ -1911,16 +1906,16 @@ async def test_delete_conversation_profile_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( - 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.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1930,7 +1925,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationProfilesClient( @@ -1941,7 +1936,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationProfilesClient(transport=transport) assert client.transport is transport @@ -1950,13 +1945,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationProfilesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationProfilesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1971,23 +1966,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 = ConversationProfilesClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationProfilesClient( + credentials=ga_credentials.AnonymousCredentials(), + ) assert isinstance(client.transport, transports.ConversationProfilesGrpcTransport,) def test_conversation_profiles_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.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1999,7 +1996,7 @@ def test_conversation_profiles_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationProfilesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2016,15 +2013,40 @@ def test_conversation_profiles_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_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.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._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.ConversationProfilesTransport( + 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_conversation_profiles_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.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2040,19 +2062,36 @@ def test_conversation_profiles_base_transport_with_credentials_file(): def test_conversation_profiles_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.dialogflow_v2beta1.services.conversation_profiles.transports.ConversationProfilesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationProfilesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversation_profiles_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) + ConversationProfilesClient() + 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_conversation_profiles_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) ConversationProfilesClient() adc.assert_called_once_with( scopes=( @@ -2063,14 +2102,44 @@ def test_conversation_profiles_auth_adc(): ) -def test_conversation_profiles_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversation_profiles_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.ConversationProfilesGrpcTransport( - 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.ConversationProfilesGrpcTransport, + transports.ConversationProfilesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversation_profiles_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", @@ -2080,6 +2149,121 @@ def test_conversation_profiles_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversation_profiles_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.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_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", + 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.ConversationProfilesGrpcTransport, grpc_helpers), + (transports.ConversationProfilesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversation_profiles_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", + 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", [ @@ -2090,7 +2274,7 @@ def test_conversation_profiles_transport_auth_adc(): def test_conversation_profiles_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: @@ -2132,7 +2316,7 @@ def test_conversation_profiles_grpc_transport_client_cert_source_for_mtls( def test_conversation_profiles_host_no_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2142,7 +2326,7 @@ def test_conversation_profiles_host_no_port(): def test_conversation_profiles_host_with_port(): client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2198,9 +2382,9 @@ def test_conversation_profiles_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", @@ -2282,7 +2466,6 @@ def test_conversation_profiles_transport_channel_mtls_with_adc(transport_class): def test_agent_path(): project = "squid" - expected = "projects/{project}/agent".format(project=project,) actual = ConversationProfilesClient.agent_path(project) assert expected == actual @@ -2299,10 +2482,35 @@ def test_parse_agent_path(): assert expected == actual -def test_conversation_profile_path(): +def test_conversation_model_path(): project = "whelk" - conversation_profile = "octopus" + location = "octopus" + conversation_model = "oyster" + expected = "projects/{project}/locations/{location}/conversationModels/{conversation_model}".format( + project=project, location=location, conversation_model=conversation_model, + ) + actual = ConversationProfilesClient.conversation_model_path( + project, location, conversation_model + ) + assert expected == actual + +def test_parse_conversation_model_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "conversation_model": "mussel", + } + path = ConversationProfilesClient.conversation_model_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationProfilesClient.parse_conversation_model_path(path) + assert expected == actual + + +def test_conversation_profile_path(): + project = "winkle" + conversation_profile = "nautilus" expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2314,8 +2522,8 @@ def test_conversation_profile_path(): def test_parse_conversation_profile_path(): expected = { - "project": "oyster", - "conversation_profile": "nudibranch", + "project": "scallop", + "conversation_profile": "abalone", } path = ConversationProfilesClient.conversation_profile_path(**expected) @@ -2325,10 +2533,9 @@ def test_parse_conversation_profile_path(): def test_document_path(): - project = "cuttlefish" - knowledge_base = "mussel" - document = "winkle" - + project = "squid" + knowledge_base = "clam" + document = "whelk" expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2338,9 +2545,9 @@ def test_document_path(): def test_parse_document_path(): expected = { - "project": "nautilus", - "knowledge_base": "scallop", - "document": "abalone", + "project": "octopus", + "knowledge_base": "oyster", + "document": "nudibranch", } path = ConversationProfilesClient.document_path(**expected) @@ -2350,9 +2557,8 @@ def test_parse_document_path(): def test_knowledge_base_path(): - project = "squid" - knowledge_base = "clam" - + project = "cuttlefish" + knowledge_base = "mussel" expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2362,8 +2568,8 @@ def test_knowledge_base_path(): def test_parse_knowledge_base_path(): expected = { - "project": "whelk", - "knowledge_base": "octopus", + "project": "winkle", + "knowledge_base": "nautilus", } path = ConversationProfilesClient.knowledge_base_path(**expected) @@ -2373,8 +2579,7 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): - billing_account = "oyster" - + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2384,7 +2589,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = ConversationProfilesClient.common_billing_account_path(**expected) @@ -2394,8 +2599,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "squid" expected = "folders/{folder}".format(folder=folder,) actual = ConversationProfilesClient.common_folder_path(folder) assert expected == actual @@ -2403,7 +2607,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = ConversationProfilesClient.common_folder_path(**expected) @@ -2413,8 +2617,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "whelk" expected = "organizations/{organization}".format(organization=organization,) actual = ConversationProfilesClient.common_organization_path(organization) assert expected == actual @@ -2422,7 +2625,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = ConversationProfilesClient.common_organization_path(**expected) @@ -2432,8 +2635,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "oyster" expected = "projects/{project}".format(project=project,) actual = ConversationProfilesClient.common_project_path(project) assert expected == actual @@ -2441,7 +2643,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = ConversationProfilesClient.common_project_path(**expected) @@ -2451,9 +2653,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2463,8 +2664,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = ConversationProfilesClient.common_location_path(**expected) @@ -2480,7 +2681,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationProfilesTransport, "_prep_wrapped_messages" ) as prep: client = ConversationProfilesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2489,6 +2690,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationProfilesClient.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/dialogflow_v2beta1/test_conversations.py b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py index daa1b4d91..d25d6bc23 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_conversations.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_conversations.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.dialogflow_v2beta1.services.conversations import ( ConversationsAsyncClient, @@ -38,13 +37,43 @@ from google.cloud.dialogflow_v2beta1.services.conversations import ConversationsClient from google.cloud.dialogflow_v2beta1.services.conversations import pagers from google.cloud.dialogflow_v2beta1.services.conversations import transports +from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.conversations.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import conversation from google.cloud.dialogflow_v2beta1.types import conversation as gcd_conversation from google.cloud.dialogflow_v2beta1.types import participant from google.cloud.dialogflow_v2beta1.types import session from google.oauth2 import service_account -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # 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(): @@ -95,7 +124,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_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_conversations_client_from_service_account_info(client_class): "client_class", [ConversationsClient, ConversationsAsyncClient,] ) def test_conversations_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: @@ -165,7 +194,7 @@ def test_conversations_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ConversationsClient, "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() @@ -453,7 +482,7 @@ def test_create_conversation( transport: str = "grpc", request_type=gcd_conversation.CreateConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -471,28 +500,21 @@ def test_create_conversation( conversation_profile="conversation_profile_value", conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -507,7 +529,7 @@ def test_create_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -517,7 +539,6 @@ def test_create_conversation_empty_call(): client.create_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() @@ -527,7 +548,7 @@ async def test_create_conversation_async( request_type=gcd_conversation.CreateConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -547,27 +568,21 @@ async def test_create_conversation_async( conversation_stage=gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_conversation.CreateConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == gcd_conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == gcd_conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -580,11 +595,12 @@ async def test_create_conversation_async_from_dict(): def test_create_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -592,7 +608,6 @@ def test_create_conversation_field_headers(): type(client.transport.create_conversation), "__call__" ) as call: call.return_value = gcd_conversation.Conversation() - client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -607,11 +622,14 @@ def test_create_conversation_field_headers(): @pytest.mark.asyncio async def test_create_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_conversation.CreateConversationRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -621,7 +639,6 @@ async def test_create_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_conversation.Conversation() ) - await client.create_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -635,7 +652,7 @@ async def test_create_conversation_field_headers_async(): def test_create_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -643,7 +660,6 @@ def test_create_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_conversation( @@ -655,14 +671,12 @@ def test_create_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") def test_create_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -676,7 +690,9 @@ def test_create_conversation_flattened_error(): @pytest.mark.asyncio async def test_create_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -699,15 +715,15 @@ async def test_create_conversation_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].conversation == gcd_conversation.Conversation(name="name_value") @pytest.mark.asyncio async def test_create_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -723,7 +739,7 @@ def test_list_conversations( transport: str = "grpc", request_type=conversation.ListConversationsRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -738,19 +754,15 @@ def test_list_conversations( call.return_value = conversation.ListConversationsResponse( next_page_token="next_page_token_value", ) - response = client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == "next_page_token_value" @@ -762,7 +774,7 @@ def test_list_conversations_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -772,7 +784,6 @@ def test_list_conversations_empty_call(): client.list_conversations() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() @@ -781,7 +792,7 @@ async def test_list_conversations_async( transport: str = "grpc_asyncio", request_type=conversation.ListConversationsRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -798,18 +809,15 @@ async def test_list_conversations_async( next_page_token="next_page_token_value", ) ) - response = await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListConversationsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -819,11 +827,12 @@ async def test_list_conversations_async_from_dict(): def test_list_conversations_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -831,7 +840,6 @@ def test_list_conversations_field_headers(): type(client.transport.list_conversations), "__call__" ) as call: call.return_value = conversation.ListConversationsResponse() - client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -846,11 +854,14 @@ def test_list_conversations_field_headers(): @pytest.mark.asyncio async def test_list_conversations_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListConversationsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -860,7 +871,6 @@ async def test_list_conversations_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListConversationsResponse() ) - await client.list_conversations(request) # Establish that the underlying gRPC stub method was called. @@ -874,7 +884,7 @@ async def test_list_conversations_field_headers_async(): def test_list_conversations_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -882,7 +892,6 @@ def test_list_conversations_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_conversations(parent="parent_value",) @@ -891,12 +900,11 @@ def test_list_conversations_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_conversations_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -908,7 +916,9 @@ def test_list_conversations_flattened_error(): @pytest.mark.asyncio async def test_list_conversations_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -928,13 +938,14 @@ async def test_list_conversations_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_conversations_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -945,7 +956,7 @@ async def test_list_conversations_flattened_error_async(): def test_list_conversations_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -990,7 +1001,7 @@ def test_list_conversations_pager(): def test_list_conversations_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1027,7 +1038,7 @@ def test_list_conversations_pages(): @pytest.mark.asyncio async def test_list_conversations_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1071,7 +1082,7 @@ async def test_list_conversations_async_pager(): @pytest.mark.asyncio async def test_list_conversations_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1114,7 +1125,7 @@ def test_get_conversation( transport: str = "grpc", request_type=conversation.GetConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1130,27 +1141,20 @@ def test_get_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1165,7 +1169,7 @@ def test_get_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1173,7 +1177,6 @@ def test_get_conversation_empty_call(): client.get_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() @@ -1182,7 +1185,7 @@ async def test_get_conversation_async( transport: str = "grpc_asyncio", request_type=conversation.GetConversationRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1200,26 +1203,20 @@ async def test_get_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.GetConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1232,17 +1229,17 @@ async def test_get_conversation_async_from_dict(): def test_get_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: call.return_value = conversation.Conversation() - client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1257,11 +1254,14 @@ def test_get_conversation_field_headers(): @pytest.mark.asyncio async def test_get_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.GetConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1269,7 +1269,6 @@ async def test_get_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.get_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1283,13 +1282,12 @@ async def test_get_conversation_field_headers_async(): def test_get_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_conversation(name="name_value",) @@ -1298,12 +1296,11 @@ def test_get_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1315,7 +1312,9 @@ def test_get_conversation_flattened_error(): @pytest.mark.asyncio async def test_get_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: @@ -1333,13 +1332,14 @@ async def test_get_conversation_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_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1353,7 +1353,7 @@ def test_complete_conversation( transport: str = "grpc", request_type=conversation.CompleteConversationRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1371,27 +1371,20 @@ def test_complete_conversation( conversation_profile="conversation_profile_value", conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) - response = client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1406,7 +1399,7 @@ def test_complete_conversation_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1416,7 +1409,6 @@ def test_complete_conversation_empty_call(): client.complete_conversation() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() @@ -1426,7 +1418,7 @@ async def test_complete_conversation_async( request_type=conversation.CompleteConversationRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1446,26 +1438,20 @@ async def test_complete_conversation_async( conversation_stage=conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE, ) ) - response = await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.CompleteConversationRequest() # Establish that the response is the type that we expect. assert isinstance(response, conversation.Conversation) - assert response.name == "name_value" - assert ( response.lifecycle_state == conversation.Conversation.LifecycleState.IN_PROGRESS ) - assert response.conversation_profile == "conversation_profile_value" - assert ( response.conversation_stage == conversation.Conversation.ConversationStage.VIRTUAL_AGENT_STAGE @@ -1478,11 +1464,12 @@ async def test_complete_conversation_async_from_dict(): def test_complete_conversation_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1490,7 +1477,6 @@ def test_complete_conversation_field_headers(): type(client.transport.complete_conversation), "__call__" ) as call: call.return_value = conversation.Conversation() - client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1505,11 +1491,14 @@ def test_complete_conversation_field_headers(): @pytest.mark.asyncio async def test_complete_conversation_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.CompleteConversationRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1519,7 +1508,6 @@ async def test_complete_conversation_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.Conversation() ) - await client.complete_conversation(request) # Establish that the underlying gRPC stub method was called. @@ -1533,7 +1521,7 @@ async def test_complete_conversation_field_headers_async(): def test_complete_conversation_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1541,7 +1529,6 @@ def test_complete_conversation_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.complete_conversation(name="name_value",) @@ -1550,12 +1537,11 @@ def test_complete_conversation_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_complete_conversation_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1567,7 +1553,9 @@ def test_complete_conversation_flattened_error(): @pytest.mark.asyncio async def test_complete_conversation_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1587,13 +1575,14 @@ async def test_complete_conversation_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_complete_conversation_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1607,7 +1596,7 @@ def test_batch_create_messages( transport: str = "grpc", request_type=conversation.BatchCreateMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1620,17 +1609,14 @@ def test_batch_create_messages( ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.BatchCreateMessagesResponse() - response = client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, conversation.BatchCreateMessagesResponse) @@ -1642,7 +1628,7 @@ def test_batch_create_messages_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1652,7 +1638,6 @@ def test_batch_create_messages_empty_call(): client.batch_create_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() @@ -1662,7 +1647,7 @@ async def test_batch_create_messages_async( request_type=conversation.BatchCreateMessagesRequest, ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1677,13 +1662,11 @@ async def test_batch_create_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.BatchCreateMessagesResponse() ) - response = await client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.BatchCreateMessagesRequest() # Establish that the response is the type that we expect. @@ -1696,11 +1679,12 @@ async def test_batch_create_messages_async_from_dict(): def test_batch_create_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.BatchCreateMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1708,7 +1692,6 @@ def test_batch_create_messages_field_headers(): type(client.transport.batch_create_messages), "__call__" ) as call: call.return_value = conversation.BatchCreateMessagesResponse() - client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1723,11 +1706,14 @@ def test_batch_create_messages_field_headers(): @pytest.mark.asyncio async def test_batch_create_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.BatchCreateMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1737,7 +1723,6 @@ async def test_batch_create_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.BatchCreateMessagesResponse() ) - await client.batch_create_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1751,7 +1736,7 @@ async def test_batch_create_messages_field_headers_async(): def test_batch_create_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1759,7 +1744,6 @@ def test_batch_create_messages_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = conversation.BatchCreateMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.batch_create_messages(parent="parent_value",) @@ -1768,12 +1752,11 @@ def test_batch_create_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_batch_create_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1785,7 +1768,9 @@ def test_batch_create_messages_flattened_error(): @pytest.mark.asyncio async def test_batch_create_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1805,13 +1790,14 @@ async def test_batch_create_messages_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_create_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1825,7 +1811,7 @@ def test_list_messages( transport: str = "grpc", request_type=conversation.ListMessagesRequest ): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1838,19 +1824,15 @@ def test_list_messages( call.return_value = conversation.ListMessagesResponse( next_page_token="next_page_token_value", ) - response = client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMessagesPager) - assert response.next_page_token == "next_page_token_value" @@ -1862,7 +1844,7 @@ def test_list_messages_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 = ConversationsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1870,7 +1852,6 @@ def test_list_messages_empty_call(): client.list_messages() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() @@ -1879,7 +1860,7 @@ async def test_list_messages_async( transport: str = "grpc_asyncio", request_type=conversation.ListMessagesRequest ): client = ConversationsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1892,18 +1873,15 @@ async def test_list_messages_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_messages(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == conversation.ListMessagesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListMessagesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1913,17 +1891,17 @@ async def test_list_messages_async_from_dict(): def test_list_messages_field_headers(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: call.return_value = conversation.ListMessagesResponse() - client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1938,11 +1916,14 @@ def test_list_messages_field_headers(): @pytest.mark.asyncio async def test_list_messages_field_headers_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = conversation.ListMessagesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1950,7 +1931,6 @@ async def test_list_messages_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( conversation.ListMessagesResponse() ) - await client.list_messages(request) # Establish that the underlying gRPC stub method was called. @@ -1964,13 +1944,12 @@ async def test_list_messages_field_headers_async(): def test_list_messages_flattened(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = conversation.ListMessagesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_messages(parent="parent_value",) @@ -1979,12 +1958,11 @@ def test_list_messages_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_messages_flattened_error(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1996,7 +1974,9 @@ def test_list_messages_flattened_error(): @pytest.mark.asyncio async def test_list_messages_flattened_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2014,13 +1994,14 @@ async def test_list_messages_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_messages_flattened_error_async(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2031,7 +2012,7 @@ async def test_list_messages_flattened_error_async(): def test_list_messages_pager(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2069,7 +2050,7 @@ def test_list_messages_pager(): def test_list_messages_pages(): - client = ConversationsClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_messages), "__call__") as call: @@ -2099,7 +2080,7 @@ def test_list_messages_pages(): @pytest.mark.asyncio async def test_list_messages_async_pager(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2136,7 +2117,7 @@ async def test_list_messages_async_pager(): @pytest.mark.asyncio async def test_list_messages_async_pages(): - client = ConversationsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ConversationsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2171,16 +2152,16 @@ async def test_list_messages_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( - 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.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -2190,7 +2171,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ConversationsClient( @@ -2201,7 +2182,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ConversationsClient(transport=transport) assert client.transport is transport @@ -2210,13 +2191,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ConversationsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ConversationsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2231,23 +2212,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 = ConversationsClient(credentials=credentials.AnonymousCredentials(),) + client = ConversationsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ConversationsGrpcTransport,) def test_conversations_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.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2259,7 +2240,7 @@ def test_conversations_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ConversationsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2277,15 +2258,40 @@ def test_conversations_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_conversations_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.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationsTransport( + 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_conversations_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.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._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.ConversationsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2301,19 +2307,36 @@ def test_conversations_base_transport_with_credentials_file(): def test_conversations_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.dialogflow_v2beta1.services.conversations.transports.ConversationsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ConversationsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_conversations_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) + ConversationsClient() + 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_conversations_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) ConversationsClient() adc.assert_called_once_with( scopes=( @@ -2324,14 +2347,44 @@ def test_conversations_auth_adc(): ) -def test_conversations_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_conversations_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.ConversationsGrpcTransport( - 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.ConversationsGrpcTransport, + transports.ConversationsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_conversations_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", @@ -2341,6 +2394,121 @@ def test_conversations_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_conversations_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.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_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", + 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.ConversationsGrpcTransport, grpc_helpers), + (transports.ConversationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_conversations_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", + 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", [ @@ -2349,7 +2517,7 @@ def test_conversations_transport_auth_adc(): ], ) def test_conversations_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: @@ -2391,7 +2559,7 @@ def test_conversations_grpc_transport_client_cert_source_for_mtls(transport_clas def test_conversations_host_no_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2401,7 +2569,7 @@ def test_conversations_host_no_port(): def test_conversations_host_with_port(): client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2455,9 +2623,9 @@ def test_conversations_transport_channel_mtls_with_client_cert_source(transport_ 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", @@ -2540,7 +2708,6 @@ def test_conversations_transport_channel_mtls_with_adc(transport_class): def test_conversation_path(): project = "squid" conversation = "clam" - expected = "projects/{project}/conversations/{conversation}".format( project=project, conversation=conversation, ) @@ -2563,7 +2730,6 @@ def test_parse_conversation_path(): def test_conversation_profile_path(): project = "oyster" conversation_profile = "nudibranch" - expected = "projects/{project}/conversationProfiles/{conversation_profile}".format( project=project, conversation_profile=conversation_profile, ) @@ -2589,7 +2755,6 @@ def test_message_path(): project = "winkle" conversation = "nautilus" message = "scallop" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -2612,7 +2777,6 @@ def test_parse_message_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2633,7 +2797,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = ConversationsClient.common_folder_path(folder) assert expected == actual @@ -2652,7 +2815,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = ConversationsClient.common_organization_path(organization) assert expected == actual @@ -2671,7 +2833,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = ConversationsClient.common_project_path(project) assert expected == actual @@ -2691,7 +2852,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -2718,7 +2878,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ConversationsTransport, "_prep_wrapped_messages" ) as prep: client = ConversationsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2727,6 +2887,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ConversationsClient.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/dialogflow_v2beta1/test_documents.py b/tests/unit/gapic/dialogflow_v2beta1/test_documents.py index 0ecfd8a80..2361f1a16 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_documents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_documents.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,30 +23,60 @@ 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.dialogflow_v2beta1.services.documents import DocumentsAsyncClient from google.cloud.dialogflow_v2beta1.services.documents import DocumentsClient from google.cloud.dialogflow_v2beta1.services.documents import pagers from google.cloud.dialogflow_v2beta1.services.documents import transports +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.documents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import document from google.cloud.dialogflow_v2beta1.types import document as gcd_document from google.cloud.dialogflow_v2beta1.types import gcs 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 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 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(): @@ -91,7 +120,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_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_documents_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [DocumentsClient, DocumentsAsyncClient,]) def test_documents_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_documents_client_get_transport_class(): def test_documents_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(DocumentsClient, "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_documents( transport: str = "grpc", request_type=document.ListDocumentsRequest ): client = DocumentsClient( - 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_documents( call.return_value = document.ListDocumentsResponse( next_page_token="next_page_token_value", ) - response = client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == "next_page_token_value" @@ -476,7 +501,7 @@ def test_list_documents_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 = DocumentsClient( - 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_documents_empty_call(): client.list_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() @@ -493,7 +517,7 @@ async def test_list_documents_async( transport: str = "grpc_asyncio", request_type=document.ListDocumentsRequest ): client = DocumentsAsyncClient( - 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_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ListDocumentsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -527,17 +548,17 @@ async def test_list_documents_async_from_dict(): def test_list_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: call.return_value = document.ListDocumentsResponse() - client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -552,11 +573,12 @@ def test_list_documents_field_headers(): @pytest.mark.asyncio async def test_list_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ListDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -564,7 +586,6 @@ async def test_list_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( document.ListDocumentsResponse() ) - await client.list_documents(request) # Establish that the underlying gRPC stub method was called. @@ -578,13 +599,12 @@ async def test_list_documents_field_headers_async(): def test_list_documents_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_documents(parent="parent_value",) @@ -593,12 +613,11 @@ def test_list_documents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_documents_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(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_documents_flattened_error(): @pytest.mark.asyncio async def test_list_documents_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -628,13 +647,12 @@ async def test_list_documents_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_documents_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(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_documents_flattened_error_async(): def test_list_documents_pager(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -683,7 +701,7 @@ def test_list_documents_pager(): def test_list_documents_pages(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_documents), "__call__") as call: @@ -713,7 +731,7 @@ def test_list_documents_pages(): @pytest.mark.asyncio async def test_list_documents_async_pager(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(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_documents_async_pager(): @pytest.mark.asyncio async def test_list_documents_async_pages(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = DocumentsAsyncClient(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_document( transport: str = "grpc", request_type=document.GetDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -804,27 +822,19 @@ def test_get_document( enable_auto_reload=True, content_uri="content_uri_value", ) - response = client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -836,7 +846,7 @@ def test_get_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -844,7 +854,6 @@ def test_get_document_empty_call(): client.get_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() @@ -853,7 +862,7 @@ async def test_get_document_async( transport: str = "grpc_asyncio", request_type=document.GetDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -872,26 +881,19 @@ async def test_get_document_async( enable_auto_reload=True, ) ) - response = await client.get_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.GetDocumentRequest() # Establish that the response is the type that we expect. assert isinstance(response, document.Document) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.mime_type == "mime_type_value" - assert response.knowledge_types == [document.Document.KnowledgeType.FAQ] - assert response.enable_auto_reload is True @@ -901,17 +903,17 @@ async def test_get_document_async_from_dict(): def test_get_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = document.Document() - client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -926,17 +928,17 @@ def test_get_document_field_headers(): @pytest.mark.asyncio async def test_get_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.GetDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) # Establish that the underlying gRPC stub method was called. @@ -950,13 +952,12 @@ async def test_get_document_field_headers_async(): def test_get_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_document(name="name_value",) @@ -965,12 +966,11 @@ def test_get_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -982,7 +982,7 @@ def test_get_document_flattened_error(): @pytest.mark.asyncio async def test_get_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_document), "__call__") as call: @@ -998,13 +998,12 @@ async def test_get_document_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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1018,7 +1017,7 @@ def test_create_document( transport: str = "grpc", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1029,13 +1028,11 @@ def test_create_document( with mock.patch.object(type(client.transport.create_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1050,7 +1047,7 @@ def test_create_document_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 = DocumentsClient( - 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 +1055,6 @@ def test_create_document_empty_call(): client.create_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() @@ -1067,7 +1063,7 @@ async def test_create_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.CreateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1080,13 +1076,11 @@ async def test_create_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.CreateDocumentRequest() # Establish that the response is the type that we expect. @@ -1099,17 +1093,17 @@ async def test_create_document_async_from_dict(): def test_create_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1124,11 +1118,12 @@ def test_create_document_field_headers(): @pytest.mark.asyncio async def test_create_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.CreateDocumentRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1136,7 +1131,6 @@ async def test_create_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_document(request) # Establish that the underlying gRPC stub method was called. @@ -1150,13 +1144,12 @@ async def test_create_document_field_headers_async(): def test_create_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__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_document( @@ -1167,14 +1160,12 @@ def test_create_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") def test_create_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1188,7 +1179,7 @@ def test_create_document_flattened_error(): @pytest.mark.asyncio async def test_create_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_document), "__call__") as call: @@ -1208,15 +1199,13 @@ async def test_create_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].document == gcd_document.Document(name="name_value") @pytest.mark.asyncio async def test_create_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1232,7 +1221,7 @@ def test_import_documents( transport: str = "grpc", request_type=document.ImportDocumentsRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1243,13 +1232,11 @@ def test_import_documents( with mock.patch.object(type(client.transport.import_documents), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.import_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() # Establish that the response is the type that we expect. @@ -1264,7 +1251,7 @@ def test_import_documents_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1272,7 +1259,6 @@ def test_import_documents_empty_call(): client.import_documents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() @@ -1281,7 +1267,7 @@ async def test_import_documents_async( transport: str = "grpc_asyncio", request_type=document.ImportDocumentsRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1294,13 +1280,11 @@ async def test_import_documents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.import_documents(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ImportDocumentsRequest() # Establish that the response is the type that we expect. @@ -1313,17 +1297,17 @@ async def test_import_documents_async_from_dict(): def test_import_documents_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ImportDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.import_documents), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.import_documents(request) # Establish that the underlying gRPC stub method was called. @@ -1338,11 +1322,12 @@ def test_import_documents_field_headers(): @pytest.mark.asyncio async def test_import_documents_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ImportDocumentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1350,7 +1335,6 @@ async def test_import_documents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.import_documents(request) # Establish that the underlying gRPC stub method was called. @@ -1367,7 +1351,7 @@ def test_delete_document( transport: str = "grpc", request_type=document.DeleteDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1378,13 +1362,11 @@ def test_delete_document( with mock.patch.object(type(client.transport.delete_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1399,7 +1381,7 @@ def test_delete_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1407,7 +1389,6 @@ def test_delete_document_empty_call(): client.delete_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() @@ -1416,7 +1397,7 @@ async def test_delete_document_async( transport: str = "grpc_asyncio", request_type=document.DeleteDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1429,13 +1410,11 @@ async def test_delete_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.DeleteDocumentRequest() # Establish that the response is the type that we expect. @@ -1448,17 +1427,17 @@ async def test_delete_document_async_from_dict(): def test_delete_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1473,11 +1452,12 @@ def test_delete_document_field_headers(): @pytest.mark.asyncio async def test_delete_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.DeleteDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1485,7 +1465,6 @@ async def test_delete_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_document(request) # Establish that the underlying gRPC stub method was called. @@ -1499,13 +1478,12 @@ async def test_delete_document_field_headers_async(): def test_delete_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__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.delete_document(name="name_value",) @@ -1514,12 +1492,11 @@ def test_delete_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1531,7 +1508,7 @@ def test_delete_document_flattened_error(): @pytest.mark.asyncio async def test_delete_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_document), "__call__") as call: @@ -1549,13 +1526,12 @@ async def test_delete_document_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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1569,7 +1545,7 @@ def test_update_document( transport: str = "grpc", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1580,13 +1556,11 @@ def test_update_document( with mock.patch.object(type(client.transport.update_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1601,7 +1575,7 @@ def test_update_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1609,7 +1583,6 @@ def test_update_document_empty_call(): client.update_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() @@ -1618,7 +1591,7 @@ async def test_update_document_async( transport: str = "grpc_asyncio", request_type=gcd_document.UpdateDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1631,13 +1604,11 @@ async def test_update_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_document.UpdateDocumentRequest() # Establish that the response is the type that we expect. @@ -1650,17 +1621,17 @@ async def test_update_document_async_from_dict(): def test_update_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1677,11 +1648,12 @@ def test_update_document_field_headers(): @pytest.mark.asyncio async def test_update_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_document.UpdateDocumentRequest() + request.document.name = "document.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1689,7 +1661,6 @@ async def test_update_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_document(request) # Establish that the underlying gRPC stub method was called. @@ -1705,32 +1676,29 @@ async def test_update_document_field_headers_async(): def test_update_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__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.update_document( document=gcd_document.Document(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].document == gcd_document.Document(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_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1738,13 +1706,13 @@ def test_update_document_flattened_error(): client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(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_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_document), "__call__") as call: @@ -1758,22 +1726,20 @@ async def test_update_document_flattened_async(): # using the keyword arguments to the method. response = await client.update_document( document=gcd_document.Document(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].document == gcd_document.Document(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_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1781,7 +1747,7 @@ async def test_update_document_flattened_error_async(): await client.update_document( gcd_document.UpdateDocumentRequest(), document=gcd_document.Document(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1789,7 +1755,7 @@ def test_reload_document( transport: str = "grpc", request_type=document.ReloadDocumentRequest ): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1800,13 +1766,11 @@ def test_reload_document( with mock.patch.object(type(client.transport.reload_document), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1821,7 +1785,7 @@ def test_reload_document_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 = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1829,7 +1793,6 @@ def test_reload_document_empty_call(): client.reload_document() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() @@ -1838,7 +1801,7 @@ async def test_reload_document_async( transport: str = "grpc_asyncio", request_type=document.ReloadDocumentRequest ): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1851,13 +1814,11 @@ async def test_reload_document_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.reload_document(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == document.ReloadDocumentRequest() # Establish that the response is the type that we expect. @@ -1870,17 +1831,17 @@ async def test_reload_document_async_from_dict(): def test_reload_document_field_headers(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1895,11 +1856,12 @@ def test_reload_document_field_headers(): @pytest.mark.asyncio async def test_reload_document_field_headers_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = document.ReloadDocumentRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1907,7 +1869,6 @@ async def test_reload_document_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.reload_document(request) # Establish that the underlying gRPC stub method was called. @@ -1921,13 +1882,12 @@ async def test_reload_document_field_headers_async(): def test_reload_document_flattened(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__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.reload_document( @@ -1938,14 +1898,12 @@ def test_reload_document_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].gcs_source == gcs.GcsSource(uri="uri_value") def test_reload_document_flattened_error(): - client = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1959,7 +1917,7 @@ def test_reload_document_flattened_error(): @pytest.mark.asyncio async def test_reload_document_flattened_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.reload_document), "__call__") as call: @@ -1979,15 +1937,13 @@ async def test_reload_document_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].gcs_source == gcs.GcsSource(uri="uri_value") @pytest.mark.asyncio async def test_reload_document_flattened_error_async(): - client = DocumentsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2002,16 +1958,16 @@ async def test_reload_document_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( - 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.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -2021,7 +1977,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = DocumentsClient( @@ -2032,7 +1988,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = DocumentsClient(transport=transport) assert client.transport is transport @@ -2041,13 +1997,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DocumentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.DocumentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2059,23 +2015,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 = DocumentsClient(credentials=credentials.AnonymousCredentials(),) + client = DocumentsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.DocumentsGrpcTransport,) def test_documents_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.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2087,7 +2043,7 @@ def test_documents_base_transport(): ) as Transport: Transport.return_value = None transport = transports.DocumentsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -2111,15 +2067,40 @@ def test_documents_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 def test_documents_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.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._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.DocumentsTransport( + 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_documents_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.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -2135,19 +2116,36 @@ def test_documents_base_transport_with_credentials_file(): def test_documents_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.dialogflow_v2beta1.services.documents.transports.DocumentsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DocumentsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_documents_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) + DocumentsClient() + 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_documents_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) DocumentsClient() adc.assert_called_once_with( scopes=( @@ -2158,14 +2156,38 @@ def test_documents_auth_adc(): ) -def test_documents_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [transports.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_documents_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.DocumentsGrpcTransport( - 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport,], +) +@requires_google_auth_lt_1_25_0 +def test_documents_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", @@ -2175,12 +2197,123 @@ def test_documents_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_documents_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.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_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", + 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.DocumentsGrpcTransport, grpc_helpers), + (transports.DocumentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_documents_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", + 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.DocumentsGrpcTransport, transports.DocumentsGrpcAsyncIOTransport], ) def test_documents_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: @@ -2222,7 +2355,7 @@ def test_documents_grpc_transport_client_cert_source_for_mtls(transport_class): def test_documents_host_no_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2232,7 +2365,7 @@ def test_documents_host_no_port(): def test_documents_host_with_port(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2283,9 +2416,9 @@ def test_documents_transport_channel_mtls_with_client_cert_source(transport_clas 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", @@ -2364,7 +2497,7 @@ def test_documents_transport_channel_mtls_with_adc(transport_class): def test_documents_grpc_lro_client(): client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2377,7 +2510,7 @@ def test_documents_grpc_lro_client(): def test_documents_grpc_lro_async_client(): client = DocumentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2392,7 +2525,6 @@ def test_document_path(): project = "squid" knowledge_base = "clam" document = "whelk" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -2415,7 +2547,6 @@ def test_parse_document_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2436,7 +2567,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = DocumentsClient.common_folder_path(folder) assert expected == actual @@ -2455,7 +2585,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = DocumentsClient.common_organization_path(organization) assert expected == actual @@ -2474,7 +2603,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = DocumentsClient.common_project_path(project) assert expected == actual @@ -2494,7 +2622,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, ) @@ -2521,7 +2648,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.DocumentsTransport, "_prep_wrapped_messages" ) as prep: client = DocumentsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2530,6 +2657,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = DocumentsClient.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/dialogflow_v2beta1/test_entity_types.py b/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py index 84f937bcb..3853f943d 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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,27 +23,57 @@ 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.dialogflow_v2beta1.services.entity_types import EntityTypesAsyncClient from google.cloud.dialogflow_v2beta1.services.entity_types import EntityTypesClient from google.cloud.dialogflow_v2beta1.services.entity_types import pagers from google.cloud.dialogflow_v2beta1.services.entity_types import transports +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import entity_type as gcd_entity_type 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(): @@ -90,7 +119,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: @@ -105,7 +134,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: @@ -156,7 +185,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() @@ -440,7 +469,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, @@ -455,19 +484,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" @@ -479,7 +504,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. @@ -489,7 +514,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() @@ -498,7 +522,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, @@ -515,18 +539,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" @@ -536,11 +557,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. @@ -548,7 +570,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. @@ -563,11 +584,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. @@ -577,7 +599,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. @@ -591,7 +612,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( @@ -599,7 +620,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( @@ -610,14 +630,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -631,7 +649,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( @@ -653,15 +671,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -674,7 +690,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( @@ -716,7 +732,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( @@ -750,7 +766,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( @@ -791,7 +807,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( @@ -831,7 +847,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, @@ -848,30 +864,22 @@ def test_get_entity_type( auto_expansion_mode=entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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 @@ -883,7 +891,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. @@ -891,7 +899,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() @@ -900,7 +907,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, @@ -919,29 +926,22 @@ async def test_get_entity_type_async( enable_fuzzy_extraction=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 @@ -951,17 +951,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. @@ -976,11 +976,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. @@ -988,7 +989,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. @@ -1002,13 +1002,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( @@ -1019,14 +1018,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1040,7 +1037,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: @@ -1060,15 +1057,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1084,7 +1079,7 @@ def test_create_entity_type( transport: str = "grpc", request_type=gcd_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, @@ -1103,30 +1098,22 @@ def test_create_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1138,7 +1125,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. @@ -1148,7 +1135,6 @@ def test_create_entity_type_empty_call(): client.create_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.CreateEntityTypeRequest() @@ -1158,7 +1144,7 @@ async def test_create_entity_type_async( request_type=gcd_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, @@ -1179,29 +1165,22 @@ async def test_create_entity_type_async( enable_fuzzy_extraction=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] == gcd_entity_type.CreateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1211,11 +1190,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 = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1223,7 +1203,6 @@ def test_create_entity_type_field_headers(): type(client.transport.create_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1238,11 +1217,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 = gcd_entity_type.CreateEntityTypeRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1252,7 +1232,6 @@ async def test_create_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.create_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1266,7 +1245,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( @@ -1274,7 +1253,6 @@ def test_create_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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( @@ -1287,16 +1265,13 @@ 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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1311,7 +1286,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( @@ -1335,17 +1310,14 @@ 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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1362,7 +1334,7 @@ def test_update_entity_type( transport: str = "grpc", request_type=gcd_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, @@ -1381,30 +1353,22 @@ def test_update_entity_type( auto_expansion_mode=gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT, enable_fuzzy_extraction=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] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1416,7 +1380,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. @@ -1426,7 +1390,6 @@ def test_update_entity_type_empty_call(): client.update_entity_type() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_entity_type.UpdateEntityTypeRequest() @@ -1436,7 +1399,7 @@ async def test_update_entity_type_async( request_type=gcd_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, @@ -1457,29 +1420,22 @@ async def test_update_entity_type_async( enable_fuzzy_extraction=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] == gcd_entity_type.UpdateEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_entity_type.EntityType) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.kind == gcd_entity_type.EntityType.Kind.KIND_MAP - assert ( response.auto_expansion_mode == gcd_entity_type.EntityType.AutoExpansionMode.AUTO_EXPANSION_MODE_DEFAULT ) - assert response.enable_fuzzy_extraction is True @@ -1489,11 +1445,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 = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1501,7 +1458,6 @@ def test_update_entity_type_field_headers(): type(client.transport.update_entity_type), "__call__" ) as call: call.return_value = gcd_entity_type.EntityType() - client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1518,11 +1474,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 = gcd_entity_type.UpdateEntityTypeRequest() + request.entity_type.name = "entity_type.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1532,7 +1489,6 @@ async def test_update_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_entity_type.EntityType() ) - await client.update_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1548,7 +1504,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( @@ -1556,29 +1512,25 @@ def test_update_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1587,13 +1539,13 @@ def test_update_entity_type_flattened_error(): gcd_entity_type.UpdateEntityTypeRequest(), entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_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( @@ -1610,24 +1562,21 @@ async def test_update_entity_type_flattened_async(): response = await client.update_entity_type( entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_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 == gcd_entity_type.EntityType(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1636,7 +1585,7 @@ async def test_update_entity_type_flattened_error_async(): gcd_entity_type.UpdateEntityTypeRequest(), entity_type=gcd_entity_type.EntityType(name="name_value"), language_code="language_code_value", - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1644,7 +1593,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, @@ -1657,13 +1606,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. @@ -1678,7 +1625,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. @@ -1688,7 +1635,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() @@ -1697,7 +1643,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, @@ -1710,13 +1656,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. @@ -1729,11 +1673,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. @@ -1741,7 +1686,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. @@ -1756,11 +1700,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. @@ -1768,7 +1713,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. @@ -1782,7 +1726,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( @@ -1790,7 +1734,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",) @@ -1799,12 +1742,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. @@ -1816,7 +1758,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( @@ -1834,13 +1776,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. @@ -1854,7 +1795,7 @@ def test_batch_update_entity_types( transport: str = "grpc", request_type=entity_type.BatchUpdateEntityTypesRequest ): 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, @@ -1867,13 +1808,11 @@ def test_batch_update_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_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.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1888,7 +1827,7 @@ def test_batch_update_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. @@ -1898,7 +1837,6 @@ def test_batch_update_entity_types_empty_call(): client.batch_update_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntityTypesRequest() @@ -1908,7 +1846,7 @@ async def test_batch_update_entity_types_async( request_type=entity_type.BatchUpdateEntityTypesRequest, ): 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, @@ -1923,13 +1861,11 @@ async def test_batch_update_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_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.BatchUpdateEntityTypesRequest() # Establish that the response is the type that we expect. @@ -1942,11 +1878,12 @@ async def test_batch_update_entity_types_async_from_dict(): def test_batch_update_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.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1954,7 +1891,6 @@ def test_batch_update_entity_types_field_headers(): type(client.transport.batch_update_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -1969,11 +1905,12 @@ def test_batch_update_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_update_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.BatchUpdateEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1983,7 +1920,6 @@ async def test_batch_update_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2000,7 +1936,7 @@ def test_batch_delete_entity_types( transport: str = "grpc", request_type=entity_type.BatchDeleteEntityTypesRequest ): 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, @@ -2013,13 +1949,11 @@ def test_batch_delete_entity_types( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_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.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2034,7 +1968,7 @@ def test_batch_delete_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. @@ -2044,7 +1978,6 @@ def test_batch_delete_entity_types_empty_call(): client.batch_delete_entity_types() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntityTypesRequest() @@ -2054,7 +1987,7 @@ async def test_batch_delete_entity_types_async( request_type=entity_type.BatchDeleteEntityTypesRequest, ): 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, @@ -2069,13 +2002,11 @@ async def test_batch_delete_entity_types_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_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.BatchDeleteEntityTypesRequest() # Establish that the response is the type that we expect. @@ -2088,11 +2019,12 @@ async def test_batch_delete_entity_types_async_from_dict(): def test_batch_delete_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.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2100,7 +2032,6 @@ def test_batch_delete_entity_types_field_headers(): type(client.transport.batch_delete_entity_types), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2115,11 +2046,12 @@ def test_batch_delete_entity_types_field_headers(): @pytest.mark.asyncio async def test_batch_delete_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.BatchDeleteEntityTypesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2129,7 +2061,6 @@ async def test_batch_delete_entity_types_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entity_types(request) # Establish that the underlying gRPC stub method was called. @@ -2143,7 +2074,7 @@ async def test_batch_delete_entity_types_field_headers_async(): def test_batch_delete_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( @@ -2151,7 +2082,6 @@ def test_batch_delete_entity_types_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.batch_delete_entity_types( @@ -2162,14 +2092,12 @@ def test_batch_delete_entity_types_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_names == ["entity_type_names_value"] def test_batch_delete_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. @@ -2183,7 +2111,7 @@ def test_batch_delete_entity_types_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_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( @@ -2205,15 +2133,13 @@ async def test_batch_delete_entity_types_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_names == ["entity_type_names_value"] @pytest.mark.asyncio async def test_batch_delete_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. @@ -2229,7 +2155,7 @@ def test_batch_create_entities( transport: str = "grpc", request_type=entity_type.BatchCreateEntitiesRequest ): 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, @@ -2242,13 +2168,11 @@ def test_batch_create_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_create_entities(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.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2263,7 +2187,7 @@ def test_batch_create_entities_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. @@ -2273,7 +2197,6 @@ def test_batch_create_entities_empty_call(): client.batch_create_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchCreateEntitiesRequest() @@ -2282,7 +2205,7 @@ async def test_batch_create_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchCreateEntitiesRequest ): 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, @@ -2297,13 +2220,11 @@ async def test_batch_create_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_create_entities(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.BatchCreateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2316,11 +2237,12 @@ async def test_batch_create_entities_async_from_dict(): def test_batch_create_entities_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.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2328,7 +2250,6 @@ def test_batch_create_entities_field_headers(): type(client.transport.batch_create_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2343,11 +2264,12 @@ def test_batch_create_entities_field_headers(): @pytest.mark.asyncio async def test_batch_create_entities_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.BatchCreateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2357,7 +2279,6 @@ async def test_batch_create_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_create_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2371,7 +2292,7 @@ async def test_batch_create_entities_field_headers_async(): def test_batch_create_entities_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( @@ -2379,7 +2300,6 @@ def test_batch_create_entities_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.batch_create_entities( @@ -2392,16 +2312,13 @@ def test_batch_create_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_create_entities_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. @@ -2416,7 +2333,7 @@ def test_batch_create_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_create_entities_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( @@ -2440,17 +2357,14 @@ async def test_batch_create_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_create_entities_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. @@ -2467,7 +2381,7 @@ def test_batch_update_entities( transport: str = "grpc", request_type=entity_type.BatchUpdateEntitiesRequest ): 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, @@ -2480,13 +2394,11 @@ def test_batch_update_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_entities(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.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2501,7 +2413,7 @@ def test_batch_update_entities_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. @@ -2511,7 +2423,6 @@ def test_batch_update_entities_empty_call(): client.batch_update_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchUpdateEntitiesRequest() @@ -2520,7 +2431,7 @@ async def test_batch_update_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchUpdateEntitiesRequest ): 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, @@ -2535,13 +2446,11 @@ async def test_batch_update_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_entities(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.BatchUpdateEntitiesRequest() # Establish that the response is the type that we expect. @@ -2554,11 +2463,12 @@ async def test_batch_update_entities_async_from_dict(): def test_batch_update_entities_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.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2566,7 +2476,6 @@ def test_batch_update_entities_field_headers(): type(client.transport.batch_update_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2581,11 +2490,12 @@ def test_batch_update_entities_field_headers(): @pytest.mark.asyncio async def test_batch_update_entities_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.BatchUpdateEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2595,7 +2505,6 @@ async def test_batch_update_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2609,7 +2518,7 @@ async def test_batch_update_entities_field_headers_async(): def test_batch_update_entities_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( @@ -2617,7 +2526,6 @@ def test_batch_update_entities_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.batch_update_entities( @@ -2630,16 +2538,13 @@ def test_batch_update_entities_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" def test_batch_update_entities_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. @@ -2654,7 +2559,7 @@ def test_batch_update_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_update_entities_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( @@ -2678,17 +2583,14 @@ async def test_batch_update_entities_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].entities == [entity_type.EntityType.Entity(value="value_value")] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_update_entities_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. @@ -2705,7 +2607,7 @@ def test_batch_delete_entities( transport: str = "grpc", request_type=entity_type.BatchDeleteEntitiesRequest ): 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, @@ -2718,13 +2620,11 @@ def test_batch_delete_entities( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_entities(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.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2739,7 +2639,7 @@ def test_batch_delete_entities_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. @@ -2749,7 +2649,6 @@ def test_batch_delete_entities_empty_call(): client.batch_delete_entities() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == entity_type.BatchDeleteEntitiesRequest() @@ -2758,7 +2657,7 @@ async def test_batch_delete_entities_async( transport: str = "grpc_asyncio", request_type=entity_type.BatchDeleteEntitiesRequest ): 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, @@ -2773,13 +2672,11 @@ async def test_batch_delete_entities_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_entities(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.BatchDeleteEntitiesRequest() # Establish that the response is the type that we expect. @@ -2792,11 +2689,12 @@ async def test_batch_delete_entities_async_from_dict(): def test_batch_delete_entities_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.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2804,7 +2702,6 @@ def test_batch_delete_entities_field_headers(): type(client.transport.batch_delete_entities), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2819,11 +2716,12 @@ def test_batch_delete_entities_field_headers(): @pytest.mark.asyncio async def test_batch_delete_entities_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.BatchDeleteEntitiesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2833,7 +2731,6 @@ async def test_batch_delete_entities_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_entities(request) # Establish that the underlying gRPC stub method was called. @@ -2847,7 +2744,7 @@ async def test_batch_delete_entities_field_headers_async(): def test_batch_delete_entities_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( @@ -2855,7 +2752,6 @@ def test_batch_delete_entities_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.batch_delete_entities( @@ -2868,16 +2764,13 @@ def test_batch_delete_entities_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_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" def test_batch_delete_entities_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. @@ -2892,7 +2785,7 @@ def test_batch_delete_entities_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_entities_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( @@ -2916,17 +2809,14 @@ async def test_batch_delete_entities_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_values == ["entity_values_value"] - assert args[0].language_code == "language_code_value" @pytest.mark.asyncio async def test_batch_delete_entities_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. @@ -2942,16 +2832,16 @@ async def test_batch_delete_entities_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( @@ -2961,7 +2851,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( @@ -2972,7 +2862,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 @@ -2981,13 +2871,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 @@ -2999,23 +2889,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", ) @@ -3027,7 +2917,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 @@ -3054,15 +2944,40 @@ def test_entity_types_base_transport(): transport.operations_client +@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.dialogflow_v2beta1.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.dialogflow_v2beta1.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", ) @@ -3078,19 +2993,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.dialogflow_v2beta1.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=( @@ -3101,14 +3033,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", @@ -3118,12 +3074,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", + 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", + 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: @@ -3165,7 +3236,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" ), @@ -3175,7 +3246,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" ), @@ -3226,9 +3297,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", @@ -3307,7 +3378,7 @@ def test_entity_types_transport_channel_mtls_with_adc(transport_class): def test_entity_types_grpc_lro_client(): client = EntityTypesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3320,7 +3391,7 @@ def test_entity_types_grpc_lro_client(): def test_entity_types_grpc_lro_async_client(): client = EntityTypesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3334,7 +3405,6 @@ def test_entity_types_grpc_lro_async_client(): def test_entity_type_path(): project = "squid" entity_type = "clam" - expected = "projects/{project}/agent/entityTypes/{entity_type}".format( project=project, entity_type=entity_type, ) @@ -3356,7 +3426,6 @@ def test_parse_entity_type_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3377,7 +3446,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = EntityTypesClient.common_folder_path(folder) assert expected == actual @@ -3396,7 +3464,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = EntityTypesClient.common_organization_path(organization) assert expected == actual @@ -3415,7 +3482,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = EntityTypesClient.common_project_path(project) assert expected == actual @@ -3435,7 +3501,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, ) @@ -3462,7 +3527,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) @@ -3471,6 +3536,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/dialogflow_v2beta1/test_environments.py b/tests/unit/gapic/dialogflow_v2beta1/test_environments.py index 78bcf4104..e7e4d92d3 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_environments.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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,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.dialogflow_v2beta1.services.environments import ( EnvironmentsAsyncClient, @@ -38,8 +37,42 @@ from google.cloud.dialogflow_v2beta1.services.environments import EnvironmentsClient from google.cloud.dialogflow_v2beta1.services.environments import pagers from google.cloud.dialogflow_v2beta1.services.environments import transports +from google.cloud.dialogflow_v2beta1.services.environments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.environments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import environment +from google.cloud.dialogflow_v2beta1.types import fulfillment from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# 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 +118,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: @@ -100,7 +133,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: @@ -151,7 +184,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() @@ -435,7 +468,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, @@ -450,19 +483,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" @@ -474,7 +503,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. @@ -484,7 +513,6 @@ def test_list_environments_empty_call(): client.list_environments() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environment.ListEnvironmentsRequest() @@ -493,7 +521,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, @@ -510,18 +538,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" @@ -531,11 +556,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. @@ -543,7 +569,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. @@ -558,11 +583,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. @@ -572,7 +598,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. @@ -586,7 +611,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( @@ -594,7 +619,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",) @@ -603,12 +627,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. @@ -620,7 +643,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( @@ -640,13 +663,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. @@ -657,7 +679,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( @@ -699,7 +721,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( @@ -733,7 +755,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( @@ -774,7 +796,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( @@ -810,241 +832,1352 @@ async def test_list_environments_async_pages(): assert page_.raw_page.next_page_token == token -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), +def test_get_environment( + transport: str = "grpc", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"credentials_file": "credentials.json"}, - 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() - # It is an error to provide scopes and a transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EnvironmentsClient( - client_options={"scopes": ["1", "2"]}, transport=transport, + # 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( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, ) + 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() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = EnvironmentsClient(transport=transport) - assert client.transport is transport + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EnvironmentsGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_get_environment_from_dict(): + test_get_environment(request_type=dict) - transport = transports.EnvironmentsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.EnvironmentsGrpcTransport, - transports.EnvironmentsGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_environment), "__call__") as call: + client.get_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentRequest() -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EnvironmentsClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.EnvironmentsGrpcTransport,) +@pytest.mark.asyncio +async def test_get_environment_async( + transport: str = "grpc_asyncio", request_type=environment.GetEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_environments_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json", + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) ) + 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() -def test_environments_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.EnvironmentsTransport( - credentials=credentials.AnonymousCredentials(), - ) + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("list_environments",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) +@pytest.mark.asyncio +async def test_get_environment_async_from_dict(): + await test_get_environment_async(request_type=dict) -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" - ) as load_creds, mock.patch( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) +def test_get_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) -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( - "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.EnvironmentsTransport() - adc.assert_called_once() + # Any value 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" -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) - EnvironmentsClient() - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id=None, - ) + # 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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_environments_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.EnvironmentsGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" - ) - adc.assert_called_once_with( - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - quota_project_id="octopus", - ) + # 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.parametrize( - "transport_class", - [transports.EnvironmentsGrpcTransport, transports.EnvironmentsGrpcAsyncIOTransport], -) -def test_environments_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() +@pytest.mark.asyncio +async def test_get_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/dialogflow", - ), - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) + # Any value 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() - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + await client.get_environment(request) -def test_environments_host_no_port(): - client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="dialogflow.googleapis.com" - ), - ) - assert client.transport._host == "dialogflow.googleapis.com:443" + # 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_environments_host_with_port(): + +def test_create_environment( + transport: str = "grpc", request_type=environment.CreateEnvironmentRequest +): client = EnvironmentsClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="dialogflow.googleapis.com:8000" - ), + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - assert client.transport._host == "dialogflow.googleapis.com:8000" - -def test_environments_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # 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() - # Check that channel is used if provided. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + 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] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_create_environment_from_dict(): + test_create_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + client.create_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.CreateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_create_environment_async( + transport: str = "grpc_asyncio", request_type=environment.CreateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + 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] == environment.CreateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_create_environment_async_from_dict(): + await test_create_environment_async(request_type=dict) + + +def test_create_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.CreateEnvironmentRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + 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] == 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_update_environment( + transport: str = "grpc", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + 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] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +def test_update_environment_from_dict(): + test_update_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + client.update_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.UpdateEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_update_environment_async( + transport: str = "grpc_asyncio", request_type=environment.UpdateEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment( + name="name_value", + description="description_value", + agent_version="agent_version_value", + state=environment.Environment.State.STOPPED, + ) + ) + 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] == environment.UpdateEnvironmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, environment.Environment) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.agent_version == "agent_version_value" + assert response.state == environment.Environment.State.STOPPED + + +@pytest.mark.asyncio +async def test_update_environment_async_from_dict(): + await test_update_environment_async(request_type=dict) + + +def test_update_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = environment.Environment() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.UpdateEnvironmentRequest() + + request.environment.name = "environment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_environment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.Environment() + ) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "environment.name=environment.name/value",) in kw[ + "metadata" + ] + + +def test_delete_environment( + transport: str = "grpc", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) 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. + assert response is None + + +def test_delete_environment_from_dict(): + test_delete_environment(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) as call: + client.delete_environment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.DeleteEnvironmentRequest() + + +@pytest.mark.asyncio +async def test_delete_environment_async( + transport: str = "grpc_asyncio", request_type=environment.DeleteEnvironmentRequest +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_environment), "__call__" + ) 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. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_environment_async_from_dict(): + await test_delete_environment_async(request_type=dict) + + +def test_delete_environment_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + 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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_environment_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.DeleteEnvironmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + 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. + 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_environment_history( + transport: str = "grpc", request_type=environment.GetEnvironmentHistoryRequest +): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + response = client.get_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.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +def test_get_environment_history_from_dict(): + test_get_environment_history(request_type=dict) + + +def test_get_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=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_environment_history), "__call__" + ) as call: + client.get_environment_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == environment.GetEnvironmentHistoryRequest() + + +@pytest.mark.asyncio +async def test_get_environment_history_async( + transport: str = "grpc_asyncio", + request_type=environment.GetEnvironmentHistoryRequest, +): + client = EnvironmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory( + parent="parent_value", next_page_token="next_page_token_value", + ) + ) + response = await client.get_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.GetEnvironmentHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.GetEnvironmentHistoryAsyncPager) + assert response.parent == "parent_value" + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_get_environment_history_async_from_dict(): + await test_get_environment_history_async(request_type=dict) + + +def test_get_environment_history_field_headers(): + client = EnvironmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = environment.EnvironmentHistory() + client.get_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] == 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_get_environment_history_field_headers_async(): + client = EnvironmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = environment.GetEnvironmentHistoryRequest() + + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_environment_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + environment.EnvironmentHistory() + ) + await client.get_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] == 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_get_environment_history_pager(): + 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_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.get_environment_history(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, environment.EnvironmentHistory.Entry) for i in results) + + +def test_get_environment_history_pages(): + 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_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = list(client.get_environment_history(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pager(): + 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_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + async_pager = await client.get_environment_history(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, environment.EnvironmentHistory.Entry) for i in responses + ) + + +@pytest.mark.asyncio +async def test_get_environment_history_async_pages(): + 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_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + next_page_token="abc", + ), + environment.EnvironmentHistory(entries=[], next_page_token="def",), + environment.EnvironmentHistory( + entries=[environment.EnvironmentHistory.Entry(),], + next_page_token="ghi", + ), + environment.EnvironmentHistory( + entries=[ + environment.EnvironmentHistory.Entry(), + environment.EnvironmentHistory.Entry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.get_environment_history(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EnvironmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EnvironmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EnvironmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EnvironmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EnvironmentsGrpcTransport, + transports.EnvironmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_environments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EnvironmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_environments", + "get_environment", + "create_environment", + "update_environment", + "delete_environment", + "get_environment_history", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@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( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.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.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EnvironmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_environments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2beta1.services.environments.transports.EnvironmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = 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(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@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(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", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@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", + 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", + 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 = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_environments_host_no_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_environments_host_with_port(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_environments_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. transport = transports.EnvironmentsGrpcTransport( host="squid.clam.whelk", channel=channel, ) @@ -1084,9 +2217,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", @@ -1166,7 +2299,6 @@ def test_environments_transport_channel_mtls_with_adc(transport_class): def test_environment_path(): project = "squid" environment = "clam" - expected = "projects/{project}/agent/environments/{environment}".format( project=project, environment=environment, ) @@ -1186,9 +2318,26 @@ def test_parse_environment_path(): assert expected == actual -def test_common_billing_account_path(): - billing_account = "oyster" +def test_fulfillment_path(): + project = "oyster" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = EnvironmentsClient.fulfillment_path(project) + assert expected == actual + +def test_parse_fulfillment_path(): + expected = { + "project": "nudibranch", + } + path = EnvironmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = EnvironmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1198,7 +2347,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "mussel", } path = EnvironmentsClient.common_billing_account_path(**expected) @@ -1208,8 +2357,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" - + folder = "winkle" expected = "folders/{folder}".format(folder=folder,) actual = EnvironmentsClient.common_folder_path(folder) assert expected == actual @@ -1217,7 +2365,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "nautilus", } path = EnvironmentsClient.common_folder_path(**expected) @@ -1227,8 +2375,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" - + organization = "scallop" expected = "organizations/{organization}".format(organization=organization,) actual = EnvironmentsClient.common_organization_path(organization) assert expected == actual @@ -1236,7 +2383,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "abalone", } path = EnvironmentsClient.common_organization_path(**expected) @@ -1246,8 +2393,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" - + project = "squid" expected = "projects/{project}".format(project=project,) actual = EnvironmentsClient.common_project_path(project) assert expected == actual @@ -1255,7 +2401,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "clam", } path = EnvironmentsClient.common_project_path(**expected) @@ -1265,9 +2411,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" - + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1277,8 +2422,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "oyster", + "location": "nudibranch", } path = EnvironmentsClient.common_location_path(**expected) @@ -1294,7 +2439,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) @@ -1303,6 +2448,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/dialogflow_v2beta1/test_fulfillments.py b/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py new file mode 100644 index 000000000..1bf52b066 --- /dev/null +++ b/tests/unit/gapic/dialogflow_v2beta1/test_fulfillments.py @@ -0,0 +1,1588 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.fulfillments import ( + FulfillmentsAsyncClient, +) +from google.cloud.dialogflow_v2beta1.services.fulfillments import FulfillmentsClient +from google.cloud.dialogflow_v2beta1.services.fulfillments import transports +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.fulfillments.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2beta1.types import fulfillment +from google.cloud.dialogflow_v2beta1.types import fulfillment as gcd_fulfillment +from google.oauth2 import service_account +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(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert FulfillmentsClient._get_default_mtls_endpoint(None) is None + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + FulfillmentsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert FulfillmentsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) +def test_fulfillments_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [FulfillmentsClient, FulfillmentsAsyncClient,]) +def test_fulfillments_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_fulfillments_client_get_transport_class(): + transport = FulfillmentsClient.get_transport_class() + available_transports = [ + transports.FulfillmentsGrpcTransport, + ] + assert transport in available_transports + + transport = FulfillmentsClient.get_transport_class("grpc") + assert transport == transports.FulfillmentsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +def test_fulfillments_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(FulfillmentsClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(FulfillmentsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "true"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc", "false"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + FulfillmentsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(FulfillmentsClient) +) +@mock.patch.object( + FulfillmentsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(FulfillmentsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_fulfillments_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (FulfillmentsClient, transports.FulfillmentsGrpcTransport, "grpc"), + ( + FulfillmentsAsyncClient, + transports.FulfillmentsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_fulfillments_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_fulfillments_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = FulfillmentsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_get_fulfillment( + transport: str = "grpc", request_type=fulfillment.GetFulfillmentRequest +): + client = FulfillmentsClient( + 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_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment( + name="name_value", + display_name="display_name_value", + enabled=True, + generic_web_service=fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), + ) + response = client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +def test_get_fulfillment_from_dict(): + test_get_fulfillment(request_type=dict) + + +def test_get_fulfillment_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 = FulfillmentsClient( + 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_fulfillment), "__call__") as call: + client.get_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_get_fulfillment_async( + transport: str = "grpc_asyncio", request_type=fulfillment.GetFulfillmentRequest +): + client = FulfillmentsAsyncClient( + 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_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment( + name="name_value", display_name="display_name_value", enabled=True, + ) + ) + response = await client.get_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == fulfillment.GetFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_get_fulfillment_async_from_dict(): + await test_get_fulfillment_async(request_type=dict) + + +def test_get_fulfillment_field_headers(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + call.return_value = fulfillment.Fulfillment() + client.get_fulfillment(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_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = fulfillment.GetFulfillmentRequest() + + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment() + ) + await client.get_fulfillment(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_fulfillment_flattened(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_fulfillment(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_fulfillment_flattened_error(): + client = FulfillmentsClient(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_fulfillment( + fulfillment.GetFulfillmentRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_fulfillment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + fulfillment.Fulfillment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_fulfillment(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_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient(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_fulfillment( + fulfillment.GetFulfillmentRequest(), name="name_value", + ) + + +def test_update_fulfillment( + transport: str = "grpc", request_type=gcd_fulfillment.UpdateFulfillmentRequest +): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment( + name="name_value", + display_name="display_name_value", + enabled=True, + generic_web_service=gcd_fulfillment.Fulfillment.GenericWebService( + uri="uri_value" + ), + ) + response = client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +def test_update_fulfillment_from_dict(): + test_update_fulfillment(request_type=dict) + + +def test_update_fulfillment_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 = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + client.update_fulfillment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + +@pytest.mark.asyncio +async def test_update_fulfillment_async( + transport: str = "grpc_asyncio", + request_type=gcd_fulfillment.UpdateFulfillmentRequest, +): + client = FulfillmentsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment( + name="name_value", display_name="display_name_value", enabled=True, + ) + ) + response = await client.update_fulfillment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_fulfillment.UpdateFulfillmentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_fulfillment.Fulfillment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.enabled is True + + +@pytest.mark.asyncio +async def test_update_fulfillment_async_from_dict(): + await test_update_fulfillment_async(request_type=dict) + + +def test_update_fulfillment_field_headers(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = "fulfillment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + call.return_value = gcd_fulfillment.Fulfillment() + client.update_fulfillment(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", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_fulfillment_field_headers_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_fulfillment.UpdateFulfillmentRequest() + + request.fulfillment.name = "fulfillment.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment() + ) + await client.update_fulfillment(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", "fulfillment.name=fulfillment.name/value",) in kw[ + "metadata" + ] + + +def test_update_fulfillment_flattened(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +def test_update_fulfillment_flattened_error(): + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_fulfillment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_fulfillment.Fulfillment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_fulfillment.Fulfillment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_fulfillment( + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].fulfillment == gcd_fulfillment.Fulfillment(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_fulfillment_flattened_error_async(): + client = FulfillmentsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_fulfillment( + gcd_fulfillment.UpdateFulfillmentRequest(), + fulfillment=gcd_fulfillment.Fulfillment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = FulfillmentsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = FulfillmentsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.FulfillmentsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.FulfillmentsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = FulfillmentsClient(credentials=ga_credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.FulfillmentsGrpcTransport,) + + +def test_fulfillments_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_fulfillments_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.FulfillmentsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_fulfillment", + "update_fulfillment", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + 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_fulfillments_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.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_fulfillments_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2beta1.services.fulfillments.transports.FulfillmentsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.FulfillmentsTransport() + adc.assert_called_once() + + +@requires_google_auth_gte_1_25_0 +def test_fulfillments_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + FulfillmentsClient() + 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_fulfillments_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) + FulfillmentsClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_fulfillments_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.FulfillmentsGrpcTransport, + transports.FulfillmentsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_fulfillments_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_fulfillments_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.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_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", + 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.FulfillmentsGrpcTransport, grpc_helpers), + (transports.FulfillmentsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_fulfillments_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", + 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.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_fulfillments_host_no_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_fulfillments_host_with_port(): + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_fulfillments_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_fulfillments_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.FulfillmentsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.FulfillmentsGrpcTransport, transports.FulfillmentsGrpcAsyncIOTransport], +) +def test_fulfillments_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_fulfillment_path(): + project = "squid" + expected = "projects/{project}/agent/fulfillment".format(project=project,) + actual = FulfillmentsClient.fulfillment_path(project) + assert expected == actual + + +def test_parse_fulfillment_path(): + expected = { + "project": "clam", + } + path = FulfillmentsClient.fulfillment_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_fulfillment_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = FulfillmentsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = FulfillmentsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder,) + actual = FulfillmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = FulfillmentsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization,) + actual = FulfillmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = FulfillmentsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project,) + actual = FulfillmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = FulfillmentsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = FulfillmentsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = FulfillmentsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = FulfillmentsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: + client = FulfillmentsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.FulfillmentsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = FulfillmentsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/dialogflow_v2beta1/test_intents.py b/tests/unit/gapic/dialogflow_v2beta1/test_intents.py index c922cc547..30ef115e5 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_intents.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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,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.dialogflow_v2beta1.services.intents import IntentsAsyncClient from google.cloud.dialogflow_v2beta1.services.intents import IntentsClient from google.cloud.dialogflow_v2beta1.services.intents import pagers from google.cloud.dialogflow_v2beta1.services.intents import transports +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.intents.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import context from google.cloud.dialogflow_v2beta1.types import intent from google.cloud.dialogflow_v2beta1.types import intent as gcd_intent 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", [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: @@ -103,7 +132,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: @@ -146,7 +175,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() @@ -418,7 +447,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, @@ -431,19 +460,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" @@ -455,7 +480,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. @@ -463,7 +488,6 @@ def test_list_intents_empty_call(): client.list_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.ListIntentsRequest() @@ -472,7 +496,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, @@ -485,18 +509,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" @@ -506,17 +527,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. @@ -531,11 +552,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. @@ -543,7 +565,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. @@ -557,13 +578,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( @@ -574,14 +594,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -595,7 +613,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: @@ -615,15 +633,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -636,7 +652,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: @@ -668,7 +684,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: @@ -692,7 +708,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( @@ -723,7 +739,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( @@ -751,7 +767,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, @@ -779,51 +795,32 @@ def test_get_intent(transport: str = "grpc", request_type=intent.GetIntentReques root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -835,7 +832,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. @@ -843,7 +840,6 @@ def test_get_intent_empty_call(): client.get_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.GetIntentRequest() @@ -852,7 +848,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, @@ -882,50 +878,32 @@ async def test_get_intent_async( parent_followup_intent_name="parent_followup_intent_name_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.webhook_state == intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -935,17 +913,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. @@ -960,17 +938,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. @@ -984,13 +962,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( @@ -1001,14 +978,12 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1022,7 +997,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: @@ -1040,15 +1015,13 @@ 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" - assert args[0].language_code == "language_code_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. @@ -1064,7 +1037,7 @@ def test_create_intent( transport: str = "grpc", request_type=gcd_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, @@ -1092,53 +1065,34 @@ def test_create_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1150,7 +1104,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. @@ -1158,7 +1112,6 @@ def test_create_intent_empty_call(): client.create_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.CreateIntentRequest() @@ -1167,7 +1120,7 @@ async def test_create_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -1199,52 +1152,34 @@ async def test_create_intent_async( parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.CreateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1254,17 +1189,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 = gcd_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 = gcd_intent.Intent() - client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1279,17 +1214,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 = gcd_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(gcd_intent.Intent()) - await client.create_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1303,13 +1238,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 = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_intent( @@ -1322,16 +1256,13 @@ 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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1346,7 +1277,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: @@ -1366,17 +1297,14 @@ 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 == gcd_intent.Intent(name="name_value") - assert args[0].language_code == "language_code_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. @@ -1393,7 +1321,7 @@ def test_update_intent( transport: str = "grpc", request_type=gcd_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, @@ -1421,53 +1349,34 @@ def test_update_intent( root_followup_intent_name="root_followup_intent_name_value", parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1479,7 +1388,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. @@ -1487,7 +1396,6 @@ def test_update_intent_empty_call(): client.update_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_intent.UpdateIntentRequest() @@ -1496,7 +1404,7 @@ async def test_update_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -1528,52 +1436,34 @@ async def test_update_intent_async( parent_followup_intent_name="parent_followup_intent_name_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] == gcd_intent.UpdateIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_intent.Intent) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert ( response.webhook_state == gcd_intent.Intent.WebhookState.WEBHOOK_STATE_ENABLED ) - assert response.priority == 898 - assert response.is_fallback is True - assert response.ml_enabled is True - assert response.ml_disabled is True - assert response.live_agent_handoff is True - assert response.end_interaction is True - assert response.input_context_names == ["input_context_names_value"] - assert response.events == ["events_value"] - assert response.action == "action_value" - assert response.reset_contexts is True - assert response.default_response_platforms == [ gcd_intent.Intent.Message.Platform.FACEBOOK ] - assert response.root_followup_intent_name == "root_followup_intent_name_value" - assert response.parent_followup_intent_name == "parent_followup_intent_name_value" @@ -1583,17 +1473,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 = gcd_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 = gcd_intent.Intent() - client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1608,17 +1498,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 = gcd_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(gcd_intent.Intent()) - await client.update_intent(request) # Establish that the underlying gRPC stub method was called. @@ -1632,18 +1522,17 @@ 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 = gcd_intent.Intent() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_intent( intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1651,16 +1540,13 @@ def test_update_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_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"]) assert args[0].language_code == "language_code_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. @@ -1668,14 +1554,14 @@ def test_update_intent_flattened_error(): client.update_intent( gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_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: @@ -1687,7 +1573,7 @@ async def test_update_intent_flattened_async(): # using the keyword arguments to the method. response = await client.update_intent( intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1695,17 +1581,14 @@ async def test_update_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].intent == gcd_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"]) assert args[0].language_code == "language_code_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. @@ -1713,7 +1596,7 @@ async def test_update_intent_flattened_error_async(): await client.update_intent( gcd_intent.UpdateIntentRequest(), intent=gcd_intent.Intent(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), language_code="language_code_value", ) @@ -1722,7 +1605,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, @@ -1733,13 +1616,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. @@ -1754,7 +1635,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. @@ -1762,7 +1643,6 @@ def test_delete_intent_empty_call(): client.delete_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.DeleteIntentRequest() @@ -1771,7 +1651,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, @@ -1782,13 +1662,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. @@ -1801,17 +1679,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. @@ -1826,17 +1704,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. @@ -1850,13 +1728,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",) @@ -1865,12 +1742,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. @@ -1882,7 +1758,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: @@ -1898,13 +1774,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. @@ -1918,7 +1793,7 @@ def test_batch_update_intents( transport: str = "grpc", request_type=intent.BatchUpdateIntentsRequest ): 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, @@ -1931,13 +1806,11 @@ def test_batch_update_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_update_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.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -1952,7 +1825,7 @@ def test_batch_update_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. @@ -1962,7 +1835,6 @@ def test_batch_update_intents_empty_call(): client.batch_update_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchUpdateIntentsRequest() @@ -1971,7 +1843,7 @@ async def test_batch_update_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchUpdateIntentsRequest ): 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, @@ -1986,13 +1858,11 @@ async def test_batch_update_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_update_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.BatchUpdateIntentsRequest() # Establish that the response is the type that we expect. @@ -2005,11 +1875,12 @@ async def test_batch_update_intents_async_from_dict(): def test_batch_update_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.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2017,7 +1888,6 @@ def test_batch_update_intents_field_headers(): type(client.transport.batch_update_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2032,11 +1902,12 @@ def test_batch_update_intents_field_headers(): @pytest.mark.asyncio async def test_batch_update_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.BatchUpdateIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2046,7 +1917,6 @@ async def test_batch_update_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_update_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2060,7 +1930,7 @@ async def test_batch_update_intents_field_headers_async(): def test_batch_update_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( @@ -2068,7 +1938,6 @@ def test_batch_update_intents_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.batch_update_intents( @@ -2083,16 +1952,14 @@ def test_batch_update_intents_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_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) def test_batch_update_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. @@ -2109,7 +1976,7 @@ def test_batch_update_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_update_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( @@ -2135,9 +2002,7 @@ async def test_batch_update_intents_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_batch_inline == intent.IntentBatch( intents=[intent.Intent(name="name_value")] ) @@ -2145,7 +2010,7 @@ async def test_batch_update_intents_flattened_async(): @pytest.mark.asyncio async def test_batch_update_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. @@ -2164,7 +2029,7 @@ def test_batch_delete_intents( transport: str = "grpc", request_type=intent.BatchDeleteIntentsRequest ): 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, @@ -2177,13 +2042,11 @@ def test_batch_delete_intents( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_delete_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.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2198,7 +2061,7 @@ def test_batch_delete_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. @@ -2208,7 +2071,6 @@ def test_batch_delete_intents_empty_call(): client.batch_delete_intents() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == intent.BatchDeleteIntentsRequest() @@ -2217,7 +2079,7 @@ async def test_batch_delete_intents_async( transport: str = "grpc_asyncio", request_type=intent.BatchDeleteIntentsRequest ): 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, @@ -2232,13 +2094,11 @@ async def test_batch_delete_intents_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_delete_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.BatchDeleteIntentsRequest() # Establish that the response is the type that we expect. @@ -2251,11 +2111,12 @@ async def test_batch_delete_intents_async_from_dict(): def test_batch_delete_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.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2263,7 +2124,6 @@ def test_batch_delete_intents_field_headers(): type(client.transport.batch_delete_intents), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2278,11 +2138,12 @@ def test_batch_delete_intents_field_headers(): @pytest.mark.asyncio async def test_batch_delete_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.BatchDeleteIntentsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2292,7 +2153,6 @@ async def test_batch_delete_intents_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_delete_intents(request) # Establish that the underlying gRPC stub method was called. @@ -2306,7 +2166,7 @@ async def test_batch_delete_intents_field_headers_async(): def test_batch_delete_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( @@ -2314,7 +2174,6 @@ def test_batch_delete_intents_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.batch_delete_intents( @@ -2325,14 +2184,12 @@ def test_batch_delete_intents_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] def test_batch_delete_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. @@ -2346,7 +2203,7 @@ def test_batch_delete_intents_flattened_error(): @pytest.mark.asyncio async def test_batch_delete_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( @@ -2368,15 +2225,13 @@ async def test_batch_delete_intents_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].intents == [intent.Intent(name="name_value")] @pytest.mark.asyncio async def test_batch_delete_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. @@ -2391,16 +2246,16 @@ async def test_batch_delete_intents_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( @@ -2410,7 +2265,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( @@ -2421,7 +2276,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 @@ -2430,13 +2285,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 @@ -2448,23 +2303,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", ) @@ -2476,7 +2331,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 @@ -2500,15 +2355,40 @@ def test_intents_base_transport(): transport.operations_client +@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.dialogflow_v2beta1.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.dialogflow_v2beta1.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", ) @@ -2524,19 +2404,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.dialogflow_v2beta1.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=( @@ -2547,14 +2444,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", @@ -2564,12 +2485,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", + 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", + 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: @@ -2611,7 +2643,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" ), @@ -2621,7 +2653,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" ), @@ -2672,9 +2704,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", @@ -2753,7 +2785,7 @@ def test_intents_transport_channel_mtls_with_adc(transport_class): def test_intents_grpc_lro_client(): client = IntentsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -2766,7 +2798,7 @@ def test_intents_grpc_lro_client(): def test_intents_grpc_lro_async_client(): client = IntentsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -2781,7 +2813,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -2805,7 +2836,6 @@ def test_parse_context_path(): def test_intent_path(): project = "cuttlefish" intent = "mussel" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -2827,7 +2857,6 @@ def test_parse_intent_path(): def test_common_billing_account_path(): billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2848,7 +2877,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = IntentsClient.common_folder_path(folder) assert expected == actual @@ -2867,7 +2895,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = IntentsClient.common_organization_path(organization) assert expected == actual @@ -2886,7 +2913,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = IntentsClient.common_project_path(project) assert expected == actual @@ -2906,7 +2932,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, ) @@ -2933,7 +2958,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) @@ -2942,6 +2967,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/dialogflow_v2beta1/test_knowledge_bases.py b/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py index 0e365bc42..d20b58149 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_knowledge_bases.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.dialogflow_v2beta1.services.knowledge_bases import ( KnowledgeBasesAsyncClient, @@ -40,10 +39,40 @@ ) from google.cloud.dialogflow_v2beta1.services.knowledge_bases import pagers from google.cloud.dialogflow_v2beta1.services.knowledge_bases import transports +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.knowledge_bases.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import knowledge_base from google.cloud.dialogflow_v2beta1.types import knowledge_base as gcd_knowledge_base 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(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_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: @@ -111,7 +140,7 @@ def test_knowledge_bases_client_from_service_account_info(client_class): "client_class", [KnowledgeBasesClient, KnowledgeBasesAsyncClient,] ) def test_knowledge_bases_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: @@ -164,7 +193,7 @@ def test_knowledge_bases_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(KnowledgeBasesClient, "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() @@ -452,7 +481,7 @@ def test_list_knowledge_bases( transport: str = "grpc", request_type=knowledge_base.ListKnowledgeBasesRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -467,19 +496,15 @@ def test_list_knowledge_bases( call.return_value = knowledge_base.ListKnowledgeBasesResponse( next_page_token="next_page_token_value", ) - response = client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKnowledgeBasesPager) - assert response.next_page_token == "next_page_token_value" @@ -491,7 +516,7 @@ def test_list_knowledge_bases_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -501,7 +526,6 @@ def test_list_knowledge_bases_empty_call(): client.list_knowledge_bases() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() @@ -511,7 +535,7 @@ async def test_list_knowledge_bases_async( request_type=knowledge_base.ListKnowledgeBasesRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -528,18 +552,15 @@ async def test_list_knowledge_bases_async( next_page_token="next_page_token_value", ) ) - response = await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.ListKnowledgeBasesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListKnowledgeBasesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -549,11 +570,12 @@ async def test_list_knowledge_bases_async_from_dict(): def test_list_knowledge_bases_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -561,7 +583,6 @@ def test_list_knowledge_bases_field_headers(): type(client.transport.list_knowledge_bases), "__call__" ) as call: call.return_value = knowledge_base.ListKnowledgeBasesResponse() - client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -576,11 +597,14 @@ def test_list_knowledge_bases_field_headers(): @pytest.mark.asyncio async def test_list_knowledge_bases_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.ListKnowledgeBasesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -590,7 +614,6 @@ async def test_list_knowledge_bases_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.ListKnowledgeBasesResponse() ) - await client.list_knowledge_bases(request) # Establish that the underlying gRPC stub method was called. @@ -604,7 +627,7 @@ async def test_list_knowledge_bases_field_headers_async(): def test_list_knowledge_bases_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -612,7 +635,6 @@ def test_list_knowledge_bases_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.ListKnowledgeBasesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_knowledge_bases(parent="parent_value",) @@ -621,12 +643,11 @@ def test_list_knowledge_bases_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_knowledge_bases_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -638,7 +659,9 @@ def test_list_knowledge_bases_flattened_error(): @pytest.mark.asyncio async def test_list_knowledge_bases_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -658,13 +681,14 @@ async def test_list_knowledge_bases_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_knowledge_bases_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -675,7 +699,7 @@ async def test_list_knowledge_bases_flattened_error_async(): def test_list_knowledge_bases_pager(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -721,7 +745,7 @@ def test_list_knowledge_bases_pager(): def test_list_knowledge_bases_pages(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -759,7 +783,7 @@ def test_list_knowledge_bases_pages(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pager(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -804,7 +828,7 @@ async def test_list_knowledge_bases_async_pager(): @pytest.mark.asyncio async def test_list_knowledge_bases_async_pages(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials,) + client = KnowledgeBasesAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -848,7 +872,7 @@ def test_get_knowledge_base( transport: str = "grpc", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -865,23 +889,17 @@ def test_get_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -893,7 +911,7 @@ def test_get_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -903,7 +921,6 @@ def test_get_knowledge_base_empty_call(): client.get_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() @@ -912,7 +929,7 @@ async def test_get_knowledge_base_async( transport: str = "grpc_asyncio", request_type=knowledge_base.GetKnowledgeBaseRequest ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -931,22 +948,17 @@ async def test_get_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.GetKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -956,11 +968,12 @@ async def test_get_knowledge_base_async_from_dict(): def test_get_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -968,7 +981,6 @@ def test_get_knowledge_base_field_headers(): type(client.transport.get_knowledge_base), "__call__" ) as call: call.return_value = knowledge_base.KnowledgeBase() - client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -983,11 +995,14 @@ def test_get_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_get_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.GetKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -997,7 +1012,6 @@ async def test_get_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( knowledge_base.KnowledgeBase() ) - await client.get_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1011,7 +1025,7 @@ async def test_get_knowledge_base_field_headers_async(): def test_get_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1019,7 +1033,6 @@ def test_get_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_knowledge_base(name="name_value",) @@ -1028,12 +1041,11 @@ def test_get_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1045,7 +1057,9 @@ def test_get_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_get_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1065,13 +1079,14 @@ async def test_get_knowledge_base_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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1085,7 +1100,7 @@ def test_create_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1102,23 +1117,17 @@ def test_create_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1130,7 +1139,7 @@ def test_create_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1140,7 +1149,6 @@ def test_create_knowledge_base_empty_call(): client.create_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() @@ -1150,7 +1158,7 @@ async def test_create_knowledge_base_async( request_type=gcd_knowledge_base.CreateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1169,22 +1177,17 @@ async def test_create_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.CreateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1194,11 +1197,12 @@ async def test_create_knowledge_base_async_from_dict(): def test_create_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1206,7 +1210,6 @@ def test_create_knowledge_base_field_headers(): type(client.transport.create_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1221,11 +1224,14 @@ def test_create_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_create_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.CreateKnowledgeBaseRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1235,7 +1241,6 @@ async def test_create_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.create_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1249,7 +1254,7 @@ async def test_create_knowledge_base_field_headers_async(): def test_create_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1257,7 +1262,6 @@ def test_create_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_knowledge_base( @@ -1269,16 +1273,14 @@ def test_create_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) def test_create_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1292,7 +1294,9 @@ def test_create_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1315,9 +1319,7 @@ async def test_create_knowledge_base_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].knowledge_base == gcd_knowledge_base.KnowledgeBase( name="name_value" ) @@ -1325,7 +1327,9 @@ async def test_create_knowledge_base_flattened_async(): @pytest.mark.asyncio async def test_create_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1341,7 +1345,7 @@ def test_delete_knowledge_base( transport: str = "grpc", request_type=knowledge_base.DeleteKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1354,13 +1358,11 @@ def test_delete_knowledge_base( ) as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1375,7 +1377,7 @@ def test_delete_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1385,7 +1387,6 @@ def test_delete_knowledge_base_empty_call(): client.delete_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() @@ -1395,7 +1396,7 @@ async def test_delete_knowledge_base_async( request_type=knowledge_base.DeleteKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1408,13 +1409,11 @@ async def test_delete_knowledge_base_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == knowledge_base.DeleteKnowledgeBaseRequest() # Establish that the response is the type that we expect. @@ -1427,11 +1426,12 @@ async def test_delete_knowledge_base_async_from_dict(): def test_delete_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1439,7 +1439,6 @@ def test_delete_knowledge_base_field_headers(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = None - client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1454,11 +1453,14 @@ def test_delete_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_delete_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = knowledge_base.DeleteKnowledgeBaseRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1466,7 +1468,6 @@ async def test_delete_knowledge_base_field_headers_async(): type(client.transport.delete_knowledge_base), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1480,7 +1481,7 @@ async def test_delete_knowledge_base_field_headers_async(): def test_delete_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1488,7 +1489,6 @@ def test_delete_knowledge_base_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_knowledge_base(name="name_value",) @@ -1497,12 +1497,11 @@ def test_delete_knowledge_base_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1514,7 +1513,9 @@ def test_delete_knowledge_base_flattened_error(): @pytest.mark.asyncio async def test_delete_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1532,13 +1533,14 @@ async def test_delete_knowledge_base_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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1552,7 +1554,7 @@ def test_update_knowledge_base( transport: str = "grpc", request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest ): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1569,23 +1571,17 @@ def test_update_knowledge_base( display_name="display_name_value", language_code="language_code_value", ) - response = client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1597,7 +1593,7 @@ def test_update_knowledge_base_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 = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1607,7 +1603,6 @@ def test_update_knowledge_base_empty_call(): client.update_knowledge_base() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() @@ -1617,7 +1612,7 @@ async def test_update_knowledge_base_async( request_type=gcd_knowledge_base.UpdateKnowledgeBaseRequest, ): client = KnowledgeBasesAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1636,22 +1631,17 @@ async def test_update_knowledge_base_async( language_code="language_code_value", ) ) - response = await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_knowledge_base.UpdateKnowledgeBaseRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_knowledge_base.KnowledgeBase) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.language_code == "language_code_value" @@ -1661,11 +1651,12 @@ async def test_update_knowledge_base_async_from_dict(): def test_update_knowledge_base_field_headers(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1673,7 +1664,6 @@ def test_update_knowledge_base_field_headers(): type(client.transport.update_knowledge_base), "__call__" ) as call: call.return_value = gcd_knowledge_base.KnowledgeBase() - client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1691,11 +1681,14 @@ def test_update_knowledge_base_field_headers(): @pytest.mark.asyncio async def test_update_knowledge_base_field_headers_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_knowledge_base.UpdateKnowledgeBaseRequest() + request.knowledge_base.name = "knowledge_base.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1705,7 +1698,6 @@ async def test_update_knowledge_base_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_knowledge_base.KnowledgeBase() ) - await client.update_knowledge_base(request) # Establish that the underlying gRPC stub method was called. @@ -1722,7 +1714,7 @@ async def test_update_knowledge_base_field_headers_async(): def test_update_knowledge_base_flattened(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1730,28 +1722,25 @@ def test_update_knowledge_base_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_knowledge_base.KnowledgeBase() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(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].knowledge_base == gcd_knowledge_base.KnowledgeBase( 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_knowledge_base_flattened_error(): - client = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1759,13 +1748,15 @@ def test_update_knowledge_base_flattened_error(): client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(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_knowledge_base_flattened_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1781,24 +1772,24 @@ async def test_update_knowledge_base_flattened_async(): # using the keyword arguments to the method. response = await client.update_knowledge_base( knowledge_base=gcd_knowledge_base.KnowledgeBase(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].knowledge_base == gcd_knowledge_base.KnowledgeBase( 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_knowledge_base_flattened_error_async(): - client = KnowledgeBasesAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1806,23 +1797,23 @@ async def test_update_knowledge_base_flattened_error_async(): await client.update_knowledge_base( gcd_knowledge_base.UpdateKnowledgeBaseRequest(), knowledge_base=gcd_knowledge_base.KnowledgeBase(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( - 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.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1832,7 +1823,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = KnowledgeBasesClient( @@ -1843,7 +1834,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = KnowledgeBasesClient(transport=transport) assert client.transport is transport @@ -1852,13 +1843,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.KnowledgeBasesGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.KnowledgeBasesGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1873,23 +1864,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 = KnowledgeBasesClient(credentials=credentials.AnonymousCredentials(),) + client = KnowledgeBasesClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.KnowledgeBasesGrpcTransport,) def test_knowledge_bases_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.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1901,7 +1892,7 @@ def test_knowledge_bases_base_transport(): ) as Transport: Transport.return_value = None transport = transports.KnowledgeBasesTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1918,15 +1909,40 @@ def test_knowledge_bases_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_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.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KnowledgeBasesTransport( + 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_knowledge_bases_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.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._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.KnowledgeBasesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1942,19 +1958,36 @@ def test_knowledge_bases_base_transport_with_credentials_file(): def test_knowledge_bases_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.dialogflow_v2beta1.services.knowledge_bases.transports.KnowledgeBasesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.KnowledgeBasesTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_knowledge_bases_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) + KnowledgeBasesClient() + 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_knowledge_bases_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) KnowledgeBasesClient() adc.assert_called_once_with( scopes=( @@ -1965,14 +1998,44 @@ def test_knowledge_bases_auth_adc(): ) -def test_knowledge_bases_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport( - 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.KnowledgeBasesGrpcTransport, + transports.KnowledgeBasesGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_knowledge_bases_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", @@ -1982,6 +2045,121 @@ def test_knowledge_bases_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_knowledge_bases_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.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_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", + 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.KnowledgeBasesGrpcTransport, grpc_helpers), + (transports.KnowledgeBasesGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_knowledge_bases_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", + 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", [ @@ -1990,7 +2168,7 @@ def test_knowledge_bases_transport_auth_adc(): ], ) def test_knowledge_bases_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: @@ -2032,7 +2210,7 @@ def test_knowledge_bases_grpc_transport_client_cert_source_for_mtls(transport_cl def test_knowledge_bases_host_no_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -2042,7 +2220,7 @@ def test_knowledge_bases_host_no_port(): def test_knowledge_bases_host_with_port(): client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -2098,9 +2276,9 @@ def test_knowledge_bases_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", @@ -2183,7 +2361,6 @@ def test_knowledge_bases_transport_channel_mtls_with_adc(transport_class): def test_knowledge_base_path(): project = "squid" knowledge_base = "clam" - expected = "projects/{project}/knowledgeBases/{knowledge_base}".format( project=project, knowledge_base=knowledge_base, ) @@ -2205,7 +2382,6 @@ def test_parse_knowledge_base_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2226,7 +2402,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = KnowledgeBasesClient.common_folder_path(folder) assert expected == actual @@ -2245,7 +2420,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = KnowledgeBasesClient.common_organization_path(organization) assert expected == actual @@ -2264,7 +2438,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = KnowledgeBasesClient.common_project_path(project) assert expected == actual @@ -2284,7 +2457,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, ) @@ -2311,7 +2483,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.KnowledgeBasesTransport, "_prep_wrapped_messages" ) as prep: client = KnowledgeBasesClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -2320,6 +2492,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = KnowledgeBasesClient.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/dialogflow_v2beta1/test_participants.py b/tests/unit/gapic/dialogflow_v2beta1/test_participants.py index 5e42b5752..a8f4ad5b7 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_participants.py +++ b/tests/unit/gapic/dialogflow_v2beta1/test_participants.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.dialogflow_v2beta1.services.participants import ( ParticipantsAsyncClient, @@ -38,6 +37,12 @@ from google.cloud.dialogflow_v2beta1.services.participants import ParticipantsClient from google.cloud.dialogflow_v2beta1.services.participants import pagers from google.cloud.dialogflow_v2beta1.services.participants import transports +from google.cloud.dialogflow_v2beta1.services.participants.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.participants.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import context @@ -47,10 +52,34 @@ from google.cloud.dialogflow_v2beta1.types import session from google.cloud.dialogflow_v2beta1.types import 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 struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import latlng_pb2 as latlng # 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.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(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_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: @@ -111,7 +140,7 @@ def test_participants_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [ParticipantsClient, ParticipantsAsyncClient,]) def test_participants_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: @@ -162,7 +191,7 @@ def test_participants_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(ParticipantsClient, "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() @@ -446,7 +475,7 @@ def test_create_participant( transport: str = "grpc", request_type=gcd_participant.CreateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -463,23 +492,17 @@ def test_create_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -491,7 +514,7 @@ def test_create_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -501,7 +524,6 @@ def test_create_participant_empty_call(): client.create_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() @@ -511,7 +533,7 @@ async def test_create_participant_async( request_type=gcd_participant.CreateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -530,22 +552,17 @@ async def test_create_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.create_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.CreateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -555,11 +572,12 @@ async def test_create_participant_async_from_dict(): def test_create_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -567,7 +585,6 @@ def test_create_participant_field_headers(): type(client.transport.create_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -582,11 +599,12 @@ def test_create_participant_field_headers(): @pytest.mark.asyncio async def test_create_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.CreateParticipantRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -596,7 +614,6 @@ async def test_create_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.create_participant(request) # Establish that the underlying gRPC stub method was called. @@ -610,7 +627,7 @@ async def test_create_participant_field_headers_async(): def test_create_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -618,7 +635,6 @@ def test_create_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_participant( @@ -630,14 +646,12 @@ def test_create_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") def test_create_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -651,7 +665,7 @@ def test_create_participant_flattened_error(): @pytest.mark.asyncio async def test_create_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -674,15 +688,13 @@ async def test_create_participant_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].participant == gcd_participant.Participant(name="name_value") @pytest.mark.asyncio async def test_create_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -698,7 +710,7 @@ def test_get_participant( transport: str = "grpc", request_type=participant.GetParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -713,23 +725,17 @@ def test_get_participant( role=participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -741,7 +747,7 @@ def test_get_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -749,7 +755,6 @@ def test_get_participant_empty_call(): client.get_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() @@ -758,7 +763,7 @@ async def test_get_participant_async( transport: str = "grpc_asyncio", request_type=participant.GetParticipantRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -775,22 +780,17 @@ async def test_get_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.get_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.GetParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.Participant) - assert response.name == "name_value" - assert response.role == participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -800,17 +800,17 @@ async def test_get_participant_async_from_dict(): def test_get_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: call.return_value = participant.Participant() - client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -825,11 +825,12 @@ def test_get_participant_field_headers(): @pytest.mark.asyncio async def test_get_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.GetParticipantRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -837,7 +838,6 @@ async def test_get_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.Participant() ) - await client.get_participant(request) # Establish that the underlying gRPC stub method was called. @@ -851,13 +851,12 @@ async def test_get_participant_field_headers_async(): def test_get_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_participant(name="name_value",) @@ -866,12 +865,11 @@ def test_get_participant_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -883,7 +881,7 @@ def test_get_participant_flattened_error(): @pytest.mark.asyncio async def test_get_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_participant), "__call__") as call: @@ -901,13 +899,12 @@ async def test_get_participant_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_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -921,7 +918,7 @@ def test_list_participants( transport: str = "grpc", request_type=participant.ListParticipantsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -936,19 +933,15 @@ def test_list_participants( call.return_value = participant.ListParticipantsResponse( next_page_token="next_page_token_value", ) - response = client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListParticipantsPager) - assert response.next_page_token == "next_page_token_value" @@ -960,7 +953,7 @@ def test_list_participants_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -970,7 +963,6 @@ def test_list_participants_empty_call(): client.list_participants() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() @@ -979,7 +971,7 @@ async def test_list_participants_async( transport: str = "grpc_asyncio", request_type=participant.ListParticipantsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -996,18 +988,15 @@ async def test_list_participants_async( next_page_token="next_page_token_value", ) ) - response = await client.list_participants(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListParticipantsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListParticipantsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1017,11 +1006,12 @@ async def test_list_participants_async_from_dict(): def test_list_participants_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1029,7 +1019,6 @@ def test_list_participants_field_headers(): type(client.transport.list_participants), "__call__" ) as call: call.return_value = participant.ListParticipantsResponse() - client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1044,11 +1033,12 @@ def test_list_participants_field_headers(): @pytest.mark.asyncio async def test_list_participants_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListParticipantsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1058,7 +1048,6 @@ async def test_list_participants_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListParticipantsResponse() ) - await client.list_participants(request) # Establish that the underlying gRPC stub method was called. @@ -1072,7 +1061,7 @@ async def test_list_participants_field_headers_async(): def test_list_participants_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1080,7 +1069,6 @@ def test_list_participants_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.ListParticipantsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_participants(parent="parent_value",) @@ -1089,12 +1077,11 @@ def test_list_participants_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_participants_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1106,7 +1093,7 @@ def test_list_participants_flattened_error(): @pytest.mark.asyncio async def test_list_participants_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1126,13 +1113,12 @@ async def test_list_participants_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_participants_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1143,7 +1129,7 @@ async def test_list_participants_flattened_error_async(): def test_list_participants_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1185,7 +1171,7 @@ def test_list_participants_pager(): def test_list_participants_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1219,7 +1205,7 @@ def test_list_participants_pages(): @pytest.mark.asyncio async def test_list_participants_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1260,7 +1246,7 @@ async def test_list_participants_async_pager(): @pytest.mark.asyncio async def test_list_participants_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1300,7 +1286,7 @@ def test_update_participant( transport: str = "grpc", request_type=gcd_participant.UpdateParticipantRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1317,23 +1303,17 @@ def test_update_participant( role=gcd_participant.Participant.Role.HUMAN_AGENT, obfuscated_external_user_id="obfuscated_external_user_id_value", ) - response = client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -1345,7 +1325,7 @@ def test_update_participant_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1355,7 +1335,6 @@ def test_update_participant_empty_call(): client.update_participant() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() @@ -1365,7 +1344,7 @@ async def test_update_participant_async( request_type=gcd_participant.UpdateParticipantRequest, ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1384,22 +1363,17 @@ async def test_update_participant_async( obfuscated_external_user_id="obfuscated_external_user_id_value", ) ) - response = await client.update_participant(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.UpdateParticipantRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.Participant) - assert response.name == "name_value" - assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT - assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" @@ -1409,11 +1383,12 @@ async def test_update_participant_async_from_dict(): def test_update_participant_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1421,7 +1396,6 @@ def test_update_participant_field_headers(): type(client.transport.update_participant), "__call__" ) as call: call.return_value = gcd_participant.Participant() - client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1438,11 +1412,12 @@ def test_update_participant_field_headers(): @pytest.mark.asyncio async def test_update_participant_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.UpdateParticipantRequest() + request.participant.name = "participant.name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1452,7 +1427,6 @@ async def test_update_participant_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.Participant() ) - await client.update_participant(request) # Establish that the underlying gRPC stub method was called. @@ -1468,7 +1442,7 @@ async def test_update_participant_field_headers_async(): def test_update_participant_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1476,26 +1450,23 @@ def test_update_participant_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.Participant() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_participant( participant=gcd_participant.Participant(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].participant == gcd_participant.Participant(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_participant_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1503,13 +1474,13 @@ def test_update_participant_flattened_error(): client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(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_participant_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1525,22 +1496,20 @@ async def test_update_participant_flattened_async(): # using the keyword arguments to the method. response = await client.update_participant( participant=gcd_participant.Participant(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].participant == gcd_participant.Participant(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_participant_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1548,7 +1517,7 @@ async def test_update_participant_flattened_error_async(): await client.update_participant( gcd_participant.UpdateParticipantRequest(), participant=gcd_participant.Participant(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1556,7 +1525,7 @@ def test_analyze_content( transport: str = "grpc", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1569,19 +1538,15 @@ def test_analyze_content( call.return_value = gcd_participant.AnalyzeContentResponse( reply_text="reply_text_value", ) - response = client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1593,7 +1558,7 @@ def test_analyze_content_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1601,7 +1566,6 @@ def test_analyze_content_empty_call(): client.analyze_content() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() @@ -1610,7 +1574,7 @@ async def test_analyze_content_async( transport: str = "grpc_asyncio", request_type=gcd_participant.AnalyzeContentRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1623,18 +1587,15 @@ async def test_analyze_content_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse(reply_text="reply_text_value",) ) - response = await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == gcd_participant.AnalyzeContentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_participant.AnalyzeContentResponse) - assert response.reply_text == "reply_text_value" @@ -1644,17 +1605,17 @@ async def test_analyze_content_async_from_dict(): def test_analyze_content_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: call.return_value = gcd_participant.AnalyzeContentResponse() - client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1669,11 +1630,12 @@ def test_analyze_content_field_headers(): @pytest.mark.asyncio async def test_analyze_content_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = gcd_participant.AnalyzeContentRequest() + request.participant = "participant/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1681,7 +1643,6 @@ async def test_analyze_content_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_participant.AnalyzeContentResponse() ) - await client.analyze_content(request) # Establish that the underlying gRPC stub method was called. @@ -1695,13 +1656,12 @@ async def test_analyze_content_field_headers_async(): def test_analyze_content_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_participant.AnalyzeContentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.analyze_content( @@ -1714,14 +1674,12 @@ def test_analyze_content_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") def test_analyze_content_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1736,7 +1694,7 @@ def test_analyze_content_flattened_error(): @pytest.mark.asyncio async def test_analyze_content_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.analyze_content), "__call__") as call: @@ -1758,15 +1716,13 @@ async def test_analyze_content_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].participant == "participant_value" - assert args[0].event_input == session.EventInput(name="name_value") @pytest.mark.asyncio async def test_analyze_content_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1783,7 +1739,7 @@ def test_suggest_articles( transport: str = "grpc", request_type=participant.SuggestArticlesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1796,21 +1752,16 @@ def test_suggest_articles( call.return_value = participant.SuggestArticlesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1822,7 +1773,7 @@ def test_suggest_articles_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1830,7 +1781,6 @@ def test_suggest_articles_empty_call(): client.suggest_articles() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() @@ -1839,7 +1789,7 @@ async def test_suggest_articles_async( transport: str = "grpc_asyncio", request_type=participant.SuggestArticlesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1854,20 +1804,16 @@ async def test_suggest_articles_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestArticlesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestArticlesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -1877,17 +1823,17 @@ async def test_suggest_articles_async_from_dict(): def test_suggest_articles_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: call.return_value = participant.SuggestArticlesResponse() - client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1902,11 +1848,12 @@ def test_suggest_articles_field_headers(): @pytest.mark.asyncio async def test_suggest_articles_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestArticlesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1914,7 +1861,6 @@ async def test_suggest_articles_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestArticlesResponse() ) - await client.suggest_articles(request) # Establish that the underlying gRPC stub method was called. @@ -1928,13 +1874,12 @@ async def test_suggest_articles_field_headers_async(): def test_suggest_articles_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestArticlesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_articles(parent="parent_value",) @@ -1943,12 +1888,11 @@ def test_suggest_articles_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_articles_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1960,7 +1904,7 @@ def test_suggest_articles_flattened_error(): @pytest.mark.asyncio async def test_suggest_articles_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.suggest_articles), "__call__") as call: @@ -1978,13 +1922,12 @@ async def test_suggest_articles_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_suggest_articles_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1998,7 +1941,7 @@ def test_suggest_faq_answers( transport: str = "grpc", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2013,21 +1956,16 @@ def test_suggest_faq_answers( call.return_value = participant.SuggestFaqAnswersResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2039,7 +1977,7 @@ def test_suggest_faq_answers_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 = ParticipantsClient( - 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 +1987,6 @@ def test_suggest_faq_answers_empty_call(): client.suggest_faq_answers() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() @@ -2058,7 +1995,7 @@ async def test_suggest_faq_answers_async( transport: str = "grpc_asyncio", request_type=participant.SuggestFaqAnswersRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2075,20 +2012,16 @@ async def test_suggest_faq_answers_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestFaqAnswersRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestFaqAnswersResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2098,11 +2031,12 @@ async def test_suggest_faq_answers_async_from_dict(): def test_suggest_faq_answers_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2110,7 +2044,6 @@ def test_suggest_faq_answers_field_headers(): type(client.transport.suggest_faq_answers), "__call__" ) as call: call.return_value = participant.SuggestFaqAnswersResponse() - client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2125,11 +2058,12 @@ def test_suggest_faq_answers_field_headers(): @pytest.mark.asyncio async def test_suggest_faq_answers_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestFaqAnswersRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2139,7 +2073,6 @@ async def test_suggest_faq_answers_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestFaqAnswersResponse() ) - await client.suggest_faq_answers(request) # Establish that the underlying gRPC stub method was called. @@ -2153,7 +2086,7 @@ async def test_suggest_faq_answers_field_headers_async(): def test_suggest_faq_answers_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2161,7 +2094,6 @@ def test_suggest_faq_answers_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestFaqAnswersResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_faq_answers(parent="parent_value",) @@ -2170,12 +2102,11 @@ def test_suggest_faq_answers_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_faq_answers_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2187,7 +2118,7 @@ def test_suggest_faq_answers_flattened_error(): @pytest.mark.asyncio async def test_suggest_faq_answers_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2207,13 +2138,12 @@ async def test_suggest_faq_answers_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_suggest_faq_answers_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2227,7 +2157,7 @@ def test_suggest_smart_replies( transport: str = "grpc", request_type=participant.SuggestSmartRepliesRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2242,21 +2172,16 @@ def test_suggest_smart_replies( call.return_value = participant.SuggestSmartRepliesResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.SuggestSmartRepliesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2268,7 +2193,7 @@ def test_suggest_smart_replies_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2278,7 +2203,6 @@ def test_suggest_smart_replies_empty_call(): client.suggest_smart_replies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() @@ -2287,7 +2211,7 @@ async def test_suggest_smart_replies_async( transport: str = "grpc_asyncio", request_type=participant.SuggestSmartRepliesRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2304,20 +2228,16 @@ async def test_suggest_smart_replies_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.SuggestSmartRepliesRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.SuggestSmartRepliesResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2327,11 +2247,12 @@ async def test_suggest_smart_replies_async_from_dict(): def test_suggest_smart_replies_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestSmartRepliesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2339,7 +2260,6 @@ def test_suggest_smart_replies_field_headers(): type(client.transport.suggest_smart_replies), "__call__" ) as call: call.return_value = participant.SuggestSmartRepliesResponse() - client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. @@ -2354,11 +2274,12 @@ def test_suggest_smart_replies_field_headers(): @pytest.mark.asyncio async def test_suggest_smart_replies_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.SuggestSmartRepliesRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2368,7 +2289,6 @@ async def test_suggest_smart_replies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.SuggestSmartRepliesResponse() ) - await client.suggest_smart_replies(request) # Establish that the underlying gRPC stub method was called. @@ -2382,7 +2302,7 @@ async def test_suggest_smart_replies_field_headers_async(): def test_suggest_smart_replies_flattened(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2390,7 +2310,6 @@ def test_suggest_smart_replies_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = participant.SuggestSmartRepliesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.suggest_smart_replies(parent="parent_value",) @@ -2399,12 +2318,11 @@ def test_suggest_smart_replies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_suggest_smart_replies_flattened_error(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2416,7 +2334,7 @@ def test_suggest_smart_replies_flattened_error(): @pytest.mark.asyncio async def test_suggest_smart_replies_flattened_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2436,13 +2354,12 @@ async def test_suggest_smart_replies_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_suggest_smart_replies_flattened_error_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2456,7 +2373,7 @@ def test_list_suggestions( transport: str = "grpc", request_type=participant.ListSuggestionsRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2469,19 +2386,15 @@ def test_list_suggestions( call.return_value = participant.ListSuggestionsResponse( next_page_token="next_page_token_value", ) - response = client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSuggestionsPager) - assert response.next_page_token == "next_page_token_value" @@ -2493,7 +2406,7 @@ def test_list_suggestions_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2501,7 +2414,6 @@ def test_list_suggestions_empty_call(): client.list_suggestions() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() @@ -2510,7 +2422,7 @@ async def test_list_suggestions_async( transport: str = "grpc_asyncio", request_type=participant.ListSuggestionsRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2525,18 +2437,15 @@ async def test_list_suggestions_async( next_page_token="next_page_token_value", ) ) - response = await client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.ListSuggestionsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSuggestionsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2546,17 +2455,17 @@ async def test_list_suggestions_async_from_dict(): def test_list_suggestions_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListSuggestionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: call.return_value = participant.ListSuggestionsResponse() - client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. @@ -2571,11 +2480,12 @@ def test_list_suggestions_field_headers(): @pytest.mark.asyncio async def test_list_suggestions_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.ListSuggestionsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2583,7 +2493,6 @@ async def test_list_suggestions_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.ListSuggestionsResponse() ) - await client.list_suggestions(request) # Establish that the underlying gRPC stub method was called. @@ -2597,7 +2506,7 @@ async def test_list_suggestions_field_headers_async(): def test_list_suggestions_pager(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: @@ -2635,7 +2544,7 @@ def test_list_suggestions_pager(): def test_list_suggestions_pages(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_suggestions), "__call__") as call: @@ -2665,7 +2574,7 @@ def test_list_suggestions_pages(): @pytest.mark.asyncio async def test_list_suggestions_async_pager(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2702,7 +2611,7 @@ async def test_list_suggestions_async_pager(): @pytest.mark.asyncio async def test_list_suggestions_async_pages(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2738,7 +2647,7 @@ def test_compile_suggestion( transport: str = "grpc", request_type=participant.CompileSuggestionRequest ): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2753,21 +2662,16 @@ def test_compile_suggestion( call.return_value = participant.CompileSuggestionResponse( latest_message="latest_message_value", context_size=1311, ) - response = client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() # Establish that the response is the type that we expect. - assert isinstance(response, participant.CompileSuggestionResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2779,7 +2683,7 @@ def test_compile_suggestion_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 = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2789,7 +2693,6 @@ def test_compile_suggestion_empty_call(): client.compile_suggestion() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() @@ -2798,7 +2701,7 @@ async def test_compile_suggestion_async( transport: str = "grpc_asyncio", request_type=participant.CompileSuggestionRequest ): client = ParticipantsAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2815,20 +2718,16 @@ async def test_compile_suggestion_async( latest_message="latest_message_value", context_size=1311, ) ) - response = await client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == participant.CompileSuggestionRequest() # Establish that the response is the type that we expect. assert isinstance(response, participant.CompileSuggestionResponse) - assert response.latest_message == "latest_message_value" - assert response.context_size == 1311 @@ -2838,11 +2737,12 @@ async def test_compile_suggestion_async_from_dict(): def test_compile_suggestion_field_headers(): - client = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.CompileSuggestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2850,7 +2750,6 @@ def test_compile_suggestion_field_headers(): type(client.transport.compile_suggestion), "__call__" ) as call: call.return_value = participant.CompileSuggestionResponse() - client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. @@ -2865,11 +2764,12 @@ def test_compile_suggestion_field_headers(): @pytest.mark.asyncio async def test_compile_suggestion_field_headers_async(): - client = ParticipantsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. request = participant.CompileSuggestionRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2879,7 +2779,6 @@ async def test_compile_suggestion_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( participant.CompileSuggestionResponse() ) - await client.compile_suggestion(request) # Establish that the underlying gRPC stub method was called. @@ -2895,16 +2794,16 @@ async def test_compile_suggestion_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( - 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.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2914,7 +2813,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ParticipantsClient( @@ -2925,7 +2824,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ParticipantsClient(transport=transport) assert client.transport is transport @@ -2934,13 +2833,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ParticipantsGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ParticipantsGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2955,23 +2854,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 = ParticipantsClient(credentials=credentials.AnonymousCredentials(),) + client = ParticipantsClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.ParticipantsGrpcTransport,) def test_participants_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.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2983,7 +2882,7 @@ def test_participants_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ParticipantsTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3005,15 +2904,40 @@ def test_participants_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_participants_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.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ParticipantsTransport( + 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_participants_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.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._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.ParticipantsTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3029,19 +2953,36 @@ def test_participants_base_transport_with_credentials_file(): def test_participants_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.dialogflow_v2beta1.services.participants.transports.ParticipantsTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ParticipantsTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_participants_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) + ParticipantsClient() + 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_participants_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) ParticipantsClient() adc.assert_called_once_with( scopes=( @@ -3052,14 +2993,44 @@ def test_participants_auth_adc(): ) -def test_participants_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_participants_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.ParticipantsGrpcTransport( - 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.ParticipantsGrpcTransport, + transports.ParticipantsGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_participants_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", @@ -3069,12 +3040,127 @@ def test_participants_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_participants_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.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_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", + 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.ParticipantsGrpcTransport, grpc_helpers), + (transports.ParticipantsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_participants_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", + 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.ParticipantsGrpcTransport, transports.ParticipantsGrpcAsyncIOTransport], ) def test_participants_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: @@ -3116,7 +3202,7 @@ def test_participants_grpc_transport_client_cert_source_for_mtls(transport_class def test_participants_host_no_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com" ), @@ -3126,7 +3212,7 @@ def test_participants_host_no_port(): def test_participants_host_with_port(): client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="dialogflow.googleapis.com:8000" ), @@ -3177,9 +3263,9 @@ def test_participants_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", @@ -3260,7 +3346,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -3285,7 +3370,6 @@ def test_document_path(): project = "cuttlefish" knowledge_base = "mussel" document = "winkle" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -3309,7 +3393,6 @@ def test_parse_document_path(): def test_intent_path(): project = "squid" intent = "clam" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -3333,7 +3416,6 @@ def test_message_path(): project = "oyster" conversation = "nudibranch" message = "cuttlefish" - expected = "projects/{project}/conversations/{conversation}/messages/{message}".format( project=project, conversation=conversation, message=message, ) @@ -3358,7 +3440,6 @@ def test_participant_path(): project = "scallop" conversation = "abalone" participant = "squid" - expected = "projects/{project}/conversations/{conversation}/participants/{participant}".format( project=project, conversation=conversation, participant=participant, ) @@ -3383,7 +3464,6 @@ def test_session_entity_type_path(): project = "oyster" session = "nudibranch" entity_type = "cuttlefish" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -3406,7 +3486,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, ) @@ -3427,7 +3506,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "squid" - expected = "folders/{folder}".format(folder=folder,) actual = ParticipantsClient.common_folder_path(folder) assert expected == actual @@ -3446,7 +3524,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "whelk" - expected = "organizations/{organization}".format(organization=organization,) actual = ParticipantsClient.common_organization_path(organization) assert expected == actual @@ -3465,7 +3542,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "oyster" - expected = "projects/{project}".format(project=project,) actual = ParticipantsClient.common_project_path(project) assert expected == actual @@ -3485,7 +3561,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, ) @@ -3512,7 +3587,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ParticipantsTransport, "_prep_wrapped_messages" ) as prep: client = ParticipantsClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3521,6 +3596,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ParticipantsClient.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/dialogflow_v2beta1/test_session_entity_types.py b/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py index 62894918b..a1e7d8484 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_session_entity_types.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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.dialogflow_v2beta1.services.session_entity_types import ( SessionEntityTypesAsyncClient, @@ -40,13 +39,43 @@ ) from google.cloud.dialogflow_v2beta1.services.session_entity_types import pagers from google.cloud.dialogflow_v2beta1.services.session_entity_types import transports +from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.session_entity_types.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import entity_type from google.cloud.dialogflow_v2beta1.types import session_entity_type from google.cloud.dialogflow_v2beta1.types import ( session_entity_type as gcd_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=gcd_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=gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() @@ -1188,7 +1199,7 @@ async def test_create_session_entity_type_async( request_type=gcd_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=gcd_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] == gcd_session_entity_type.CreateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_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 = gcd_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 = gcd_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 = gcd_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( gcd_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 = gcd_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,16 +1321,16 @@ 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 == gcd_session_entity_type.SessionEntityType( name="name_value" ) 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. @@ -1337,7 +1347,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. @@ -1363,9 +1373,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 == gcd_session_entity_type.SessionEntityType( name="name_value" ) @@ -1374,7 +1382,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 @@ -1394,7 +1402,7 @@ def test_update_session_entity_type( request_type=gcd_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, @@ -1410,21 +1418,16 @@ def test_update_session_entity_type( name="name_value", entity_override_mode=gcd_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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1439,7 +1442,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. @@ -1449,7 +1452,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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() @@ -1459,7 +1461,7 @@ async def test_update_session_entity_type_async( request_type=gcd_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, @@ -1477,20 +1479,16 @@ async def test_update_session_entity_type_async( entity_override_mode=gcd_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] == gcd_session_entity_type.UpdateSessionEntityTypeRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session_entity_type.SessionEntityType) - assert response.name == "name_value" - assert ( response.entity_override_mode == gcd_session_entity_type.SessionEntityType.EntityOverrideMode.ENTITY_OVERRIDE_MODE_OVERRIDE @@ -1503,11 +1501,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 = gcd_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. @@ -1515,7 +1516,6 @@ def test_update_session_entity_type_field_headers(): type(client.transport.update_session_entity_type), "__call__" ) as call: call.return_value = gcd_session_entity_type.SessionEntityType() - client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1534,12 +1534,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 = gcd_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. @@ -1549,7 +1550,6 @@ async def test_update_session_entity_type_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session_entity_type.SessionEntityType() ) - await client.update_session_entity_type(request) # Establish that the underlying gRPC stub method was called. @@ -1566,7 +1566,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( @@ -1574,30 +1576,29 @@ def test_update_session_entity_type_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_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=gcd_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 == gcd_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. @@ -1607,14 +1608,14 @@ def test_update_session_entity_type_flattened_error(): session_entity_type=gcd_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. @@ -1633,25 +1634,23 @@ async def test_update_session_entity_type_flattened_async(): session_entity_type=gcd_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 == gcd_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 @@ -1662,7 +1661,7 @@ async def test_update_session_entity_type_flattened_error_async(): session_entity_type=gcd_session_entity_type.SessionEntityType( name="name_value" ), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1671,7 +1670,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, @@ -1684,13 +1683,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. @@ -1705,7 +1702,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. @@ -1715,7 +1712,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() @@ -1725,7 +1721,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, @@ -1738,13 +1734,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. @@ -1757,11 +1751,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. @@ -1769,7 +1766,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. @@ -1785,12 +1781,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. @@ -1798,7 +1795,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. @@ -1812,7 +1808,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( @@ -1820,7 +1818,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",) @@ -1829,12 +1826,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. @@ -1847,7 +1845,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. @@ -1866,14 +1864,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 @@ -1887,16 +1884,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( @@ -1906,7 +1903,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( @@ -1917,7 +1914,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 @@ -1926,13 +1923,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 @@ -1947,23 +1944,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", ) @@ -1975,7 +1974,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 @@ -1992,15 +1991,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.dialogflow_v2beta1.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.dialogflow_v2beta1.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", ) @@ -2016,19 +2040,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.dialogflow_v2beta1.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=( @@ -2039,14 +2080,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", @@ -2056,6 +2127,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", + 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", + 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", [ @@ -2066,7 +2252,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: @@ -2108,7 +2294,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" ), @@ -2118,7 +2304,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" ), @@ -2174,9 +2360,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", @@ -2260,7 +2446,6 @@ def test_session_entity_type_path(): project = "squid" session = "clam" entity_type = "whelk" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -2285,7 +2470,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -2306,7 +2490,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = SessionEntityTypesClient.common_folder_path(folder) assert expected == actual @@ -2325,7 +2508,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionEntityTypesClient.common_organization_path(organization) assert expected == actual @@ -2344,7 +2526,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = SessionEntityTypesClient.common_project_path(project) assert expected == actual @@ -2364,7 +2545,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, ) @@ -2391,7 +2571,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) @@ -2400,6 +2580,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/dialogflow_v2beta1/test_sessions.py b/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py index 81d572606..865f7ce90 100644 --- a/tests/unit/gapic/dialogflow_v2beta1/test_sessions.py +++ b/tests/unit/gapic/dialogflow_v2beta1/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.dialogflow_v2beta1.services.sessions import SessionsAsyncClient from google.cloud.dialogflow_v2beta1.services.sessions import SessionsClient from google.cloud.dialogflow_v2beta1.services.sessions import transports +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.sessions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.dialogflow_v2beta1.types import agent from google.cloud.dialogflow_v2beta1.types import audio_config from google.cloud.dialogflow_v2beta1.types import context @@ -43,10 +48,34 @@ from google.cloud.dialogflow_v2beta1.types import session as gcd_session from google.cloud.dialogflow_v2beta1.types import 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 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 field_mask_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 +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", [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: @@ -105,7 +134,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: @@ -150,7 +179,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() @@ -426,7 +455,7 @@ def test_detect_intent( transport: str = "grpc", request_type=gcd_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, @@ -439,21 +468,16 @@ def test_detect_intent( call.return_value = gcd_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] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. - assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -465,7 +489,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. @@ -473,7 +497,6 @@ def test_detect_intent_empty_call(): client.detect_intent() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == gcd_session.DetectIntentRequest() @@ -482,7 +505,7 @@ async def test_detect_intent_async( transport: str = "grpc_asyncio", request_type=gcd_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, @@ -497,20 +520,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] == gcd_session.DetectIntentRequest() # Establish that the response is the type that we expect. assert isinstance(response, gcd_session.DetectIntentResponse) - assert response.response_id == "response_id_value" - assert response.output_audio == b"output_audio_blob" @@ -520,17 +539,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 = gcd_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 = gcd_session.DetectIntentResponse() - client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -545,11 +564,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 = gcd_session.DetectIntentRequest() + request.session = "session/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -557,7 +577,6 @@ async def test_detect_intent_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( gcd_session.DetectIntentResponse() ) - await client.detect_intent(request) # Establish that the underlying gRPC stub method was called. @@ -571,13 +590,12 @@ async def test_detect_intent_field_headers_async(): def test_detect_intent_flattened(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_session.DetectIntentResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.detect_intent( @@ -593,9 +611,7 @@ def test_detect_intent_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -604,7 +620,7 @@ def test_detect_intent_flattened(): def test_detect_intent_flattened_error(): - client = SessionsClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -622,7 +638,7 @@ def test_detect_intent_flattened_error(): @pytest.mark.asyncio async def test_detect_intent_flattened_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.detect_intent), "__call__") as call: @@ -647,9 +663,7 @@ async def test_detect_intent_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].session == "session_value" - assert args[0].query_input == gcd_session.QueryInput( audio_config=audio_config.InputAudioConfig( audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16 @@ -659,7 +673,7 @@ async def test_detect_intent_flattened_async(): @pytest.mark.asyncio async def test_detect_intent_flattened_error_async(): - client = SessionsAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = SessionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -679,13 +693,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. @@ -694,13 +707,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. @@ -717,13 +728,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. @@ -735,13 +745,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. @@ -757,16 +765,16 @@ async def test_streaming_detect_intent_async_from_dict(): 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( @@ -776,7 +784,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( @@ -787,7 +795,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 @@ -796,13 +804,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 @@ -814,23 +822,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", ) @@ -842,7 +850,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 @@ -856,15 +864,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.dialogflow_v2beta1.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.dialogflow_v2beta1.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", ) @@ -880,19 +913,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.dialogflow_v2beta1.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=( @@ -903,14 +953,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", @@ -920,12 +994,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", + 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", + 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: @@ -967,7 +1152,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" ), @@ -977,7 +1162,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" ), @@ -1028,9 +1213,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", @@ -1111,7 +1296,6 @@ def test_context_path(): project = "squid" session = "clam" context = "whelk" - expected = "projects/{project}/agent/sessions/{session}/contexts/{context}".format( project=project, session=session, context=context, ) @@ -1136,7 +1320,6 @@ def test_document_path(): project = "cuttlefish" knowledge_base = "mussel" document = "winkle" - expected = "projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}".format( project=project, knowledge_base=knowledge_base, document=document, ) @@ -1160,7 +1343,6 @@ def test_parse_document_path(): def test_intent_path(): project = "squid" intent = "clam" - expected = "projects/{project}/agent/intents/{intent}".format( project=project, intent=intent, ) @@ -1183,7 +1365,6 @@ def test_parse_intent_path(): def test_session_path(): project = "oyster" session = "nudibranch" - expected = "projects/{project}/agent/sessions/{session}".format( project=project, session=session, ) @@ -1207,7 +1388,6 @@ def test_session_entity_type_path(): project = "winkle" session = "nautilus" entity_type = "scallop" - expected = "projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}".format( project=project, session=session, entity_type=entity_type, ) @@ -1230,7 +1410,6 @@ def test_parse_session_entity_type_path(): def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1251,7 +1430,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder,) actual = SessionsClient.common_folder_path(folder) assert expected == actual @@ -1270,7 +1448,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization,) actual = SessionsClient.common_organization_path(organization) assert expected == actual @@ -1289,7 +1466,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project,) actual = SessionsClient.common_project_path(project) assert expected == actual @@ -1309,7 +1485,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1336,7 +1511,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) @@ -1345,6 +1520,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/dialogflow_v2beta1/test_versions.py b/tests/unit/gapic/dialogflow_v2beta1/test_versions.py new file mode 100644 index 000000000..66877b17f --- /dev/null +++ b/tests/unit/gapic/dialogflow_v2beta1/test_versions.py @@ -0,0 +1,2273 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.dialogflow_v2beta1.services.versions import VersionsAsyncClient +from google.cloud.dialogflow_v2beta1.services.versions import VersionsClient +from google.cloud.dialogflow_v2beta1.services.versions import pagers +from google.cloud.dialogflow_v2beta1.services.versions import transports +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.dialogflow_v2beta1.services.versions.transports.base import ( + _GOOGLE_AUTH_VERSION, +) +from google.cloud.dialogflow_v2beta1.types import version +from google.cloud.dialogflow_v2beta1.types import version as gcd_version +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# 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(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert VersionsClient._get_default_mtls_endpoint(None) is None + assert VersionsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + VersionsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + VersionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert VersionsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) +def test_versions_client_from_service_account_info(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +@pytest.mark.parametrize("client_class", [VersionsClient, VersionsAsyncClient,]) +def test_versions_client_from_service_account_file(client_class): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_versions_client_get_transport_class(): + transport = VersionsClient.get_transport_class() + available_transports = [ + transports.VersionsGrpcTransport, + ] + assert transport in available_transports + + transport = VersionsClient.get_transport_class("grpc") + assert transport == transports.VersionsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) +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=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(VersionsClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "true"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (VersionsClient, transports.VersionsGrpcTransport, "grpc", "false"), + ( + VersionsAsyncClient, + transports.VersionsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + VersionsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(VersionsClient) +) +@mock.patch.object( + VersionsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(VersionsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_versions_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (VersionsClient, transports.VersionsGrpcTransport, "grpc"), + (VersionsAsyncClient, transports.VersionsGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_versions_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_versions_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = VersionsClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_list_versions( + transport: str = "grpc", request_type=version.ListVersionsRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + 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" + + +def test_list_versions_from_dict(): + test_list_versions(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + client.list_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.ListVersionsRequest() + + +@pytest.mark.asyncio +async def test_list_versions_async( + transport: str = "grpc_asyncio", request_type=version.ListVersionsRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + 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" + + +@pytest.mark.asyncio +async def test_list_versions_async_from_dict(): + await test_list_versions_async(request_type=dict) + + +def test_list_versions_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_versions_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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 = grpc_helpers_async.FakeUnaryUnaryCall( + version.ListVersionsResponse() + ) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_versions_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +def test_list_versions_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_versions( + version.ListVersionsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_versions_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_versions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.ListVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.ListVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_versions(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_versions_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_versions( + version.ListVersionsRequest(), parent="parent_value", + ) + + +def test_list_versions_pager(): + 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: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_versions(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, version.Version) for i in results) + + +def test_list_versions_pages(): + 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: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + pages = list(client.list_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_versions_async_pager(): + 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__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + async_pager = await client.list_versions(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, version.Version) for i in responses) + + +@pytest.mark.asyncio +async def test_list_versions_async_pages(): + 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__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + version.ListVersionsResponse( + versions=[version.Version(), version.Version(), version.Version(),], + next_page_token="abc", + ), + version.ListVersionsResponse(versions=[], next_page_token="def",), + version.ListVersionsResponse( + versions=[version.Version(),], next_page_token="ghi", + ), + version.ListVersionsResponse( + versions=[version.Version(), version.Version(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_versions(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_version(transport: str = "grpc", request_type=version.GetVersionRequest): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + 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.description == "description_value" + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +def test_get_version_from_dict(): + test_get_version(request_type=dict) + + +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=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_version), "__call__") as call: + client.get_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.GetVersionRequest() + + +@pytest.mark.asyncio +async def test_get_version_async( + transport: str = "grpc_asyncio", request_type=version.GetVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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.description == "description_value" + assert response.version_number == 1518 + assert response.status == version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_get_version_async_from_dict(): + await test_get_version_async(request_type=dict) + + +def test_get_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + 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_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + 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_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # 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_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_version( + version.GetVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_version(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_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_version( + version.GetVersionRequest(), name="name_value", + ) + + +def test_create_version( + transport: str = "grpc", request_type=gcd_version.CreateVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + 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] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_create_version_from_dict(): + test_create_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + client.create_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.CreateVersionRequest() + + +@pytest.mark.asyncio +async def test_create_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.CreateVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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] == gcd_version.CreateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_create_version_async_from_dict(): + await test_create_version_async(request_type=dict) + + +def test_create_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = gcd_version.Version() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_version( + parent="parent_value", version=gcd_version.Version(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") + + +def test_create_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_version( + gcd_version.CreateVersionRequest(), + parent="parent_value", + version=gcd_version.Version(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_version( + parent="parent_value", version=gcd_version.Version(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].parent == "parent_value" + assert args[0].version == gcd_version.Version(name="name_value") + + +@pytest.mark.asyncio +async def test_create_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_version( + gcd_version.CreateVersionRequest(), + parent="parent_value", + version=gcd_version.Version(name="name_value"), + ) + + +def test_update_version( + transport: str = "grpc", request_type=gcd_version.UpdateVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + 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] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +def test_update_version_from_dict(): + test_update_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + client.update_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_version.UpdateVersionRequest() + + +@pytest.mark.asyncio +async def test_update_version_async( + transport: str = "grpc_asyncio", request_type=gcd_version.UpdateVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_version.Version( + name="name_value", + description="description_value", + version_number=1518, + status=gcd_version.Version.VersionStatus.IN_PROGRESS, + ) + ) + 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] == gcd_version.UpdateVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_version.Version) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.version_number == 1518 + assert response.status == gcd_version.Version.VersionStatus.IN_PROGRESS + + +@pytest.mark.asyncio +async def test_update_version_async_from_dict(): + await test_update_version_async(request_type=dict) + + +def test_update_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = gcd_version.Version() + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = gcd_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 = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + 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] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "version.name=version.name/value",) in kw[ + "metadata" + ] + + +def test_update_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_version( + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name="name_value") + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) + + +def test_update_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_version.Version() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_version.Version()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_version( + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].version == gcd_version.Version(name="name_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=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_version( + gcd_version.UpdateVersionRequest(), + version=gcd_version.Version(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_version( + transport: str = "grpc", request_type=version.DeleteVersionRequest +): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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. + assert response is None + + +def test_delete_version_from_dict(): + test_delete_version(request_type=dict) + + +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=ga_credentials.AnonymousCredentials(), transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: + client.delete_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == version.DeleteVersionRequest() + + +@pytest.mark.asyncio +async def test_delete_version_async( + transport: str = "grpc_asyncio", request_type=version.DeleteVersionRequest +): + client = VersionsAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_version_async_from_dict(): + await test_delete_version_async(request_type=dict) + + +def test_delete_version_field_headers(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_version_field_headers_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = version.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. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_version_flattened(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.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",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +def test_delete_version_flattened_error(): + client = VersionsClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_version( + version.DeleteVersionRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_version_flattened_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_version(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_version_flattened_error_async(): + client = VersionsAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_version( + version.DeleteVersionRequest(), name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VersionsClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VersionsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VersionsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VersionsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_versions_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.VersionsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_versions", + "get_version", + "create_version", + "update_version", + "delete_version", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +@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( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=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.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VersionsTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_versions_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.dialogflow_v2beta1.services.versions.transports.VersionsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = 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(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=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport,], +) +@requires_google_auth_gte_1_25_0 +def test_versions_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + 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", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@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", + 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", + 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 = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_versions_host_no_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:443" + + +def test_versions_host_with_port(): + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + ) + assert client.transport._host == "dialogflow.googleapis.com:8000" + + +def test_versions_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_versions_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VersionsGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], +) +def test_versions_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VersionsGrpcTransport, transports.VersionsGrpcAsyncIOTransport], +) +def test_versions_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_version_path(): + project = "squid" + version = "clam" + expected = "projects/{project}/agent/versions/{version}".format( + project=project, version=version, + ) + actual = VersionsClient.version_path(project, version) + assert expected == actual + + +def test_parse_version_path(): + expected = { + "project": "whelk", + "version": "octopus", + } + path = VersionsClient.version_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_version_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = VersionsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = VersionsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder,) + actual = VersionsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = VersionsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization,) + actual = VersionsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = VersionsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project,) + actual = VersionsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = VersionsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + actual = VersionsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = VersionsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VersionsClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: + client = VersionsClient( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.VersionsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = VersionsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info)